지난 시간 동안 SQL 데이터베이스에 데이터를 삽입하려고했습니다. 하나 또는 다른 이유로 데이터베이스에 연결할 수 있지만 데이터가 데이터베이스에 삽입되지 않습니다. SQL 문을 데이터베이스에서 직접 실행하면 작동하는 것 같습니다. 따라서 저는이 진술서가 정확하다고 결론을 내릴 수있었습니다. 또한 런타임에는 오류가 없었습니다. 다음 C# 코드가 있습니다.mbf 데이터베이스에 데이터를 삽입 할 수 없습니다.
//Neither of these statements seem to work.
string sqlStatement = "INSERT INTO dbo.eventTable (colA, colB, colC, colD, colE, colF, colG, colH, colI) VALUES (@a,@b,@c,@d,@e,@f,@g,@h,@i)";
string altSqlStatement = "INSERT INTO dbo.eventTable (colA, colB, colC, colD, colE, colF, colG, colH, colI) VALUES (@a,@b,@c,@d,@e,@f,@g,@h,@i)";
foreach (DataRow row in importData.Rows)
{
using (SqlConnection conn = new SqlConnection(form1.Properties.Settings.Default.showConnectionString))
{
using (SqlCommand insertCommand = new SqlCommand())
{
insertCommand.Connection = conn;
insertCommand.CommandText = sqlStatement;
insertCommand.CommandType = CommandType.Text;
insertCommand.Parameters.AddWithValue("@a", row["CUE"].ToString());
insertCommand.Parameters.AddWithValue("@b", row["HH"].ToString());
insertCommand.Parameters.AddWithValue("@c", row["MM"].ToString());
insertCommand.Parameters.AddWithValue("@d", row["SS"].ToString());
insertCommand.Parameters.AddWithValue("@e", row["FF"].ToString());
insertCommand.Parameters.AddWithValue("@f", row["ADDR"].ToString());
insertCommand.Parameters.AddWithValue("@g", row["Event Description"].ToString());
insertCommand.Parameters.AddWithValue("@h", row["CAL"].ToString());
insertCommand.Parameters.AddWithValue("@i", row["PFT"].ToString());
try
{
conn.Open();
int _affected = insertCommand.ExecuteNonQuery();
}
catch(SqlException e)
{
// do something with the exception
}
}
}
}
연결 매개 변수를 false로 변경하면 오류가 발생하므로 올바른 것으로 보입니다.
도움을 주시면 감사하겠습니다.
감사합니다. 템플릿으로이 기능을 사용
알렉스
세 가지를 내부 안쪽에 있어야한다 (SqlCommand insertCommand = new SqlCommand (sqlStatment, conn))'2. 데이터베이스의 모든 열의 형식이'varchar' 또는'char'인지 확인하고, 모든 매개 변수를'string'으로 변환하면됩니다. 거기에는 약간의 갈등이 있습니다. 3.'_affected' 변수를 보면서'insertCommand.ExecuteNonQuery();'의 결과를 디버그하고 검사하십시오. –