我在azure中调用一个web服务,并使用以下方法填充一个DB。我不知道怎么了。
using (SqlConnection conn = new SqlConnection(cs))
{
using (SqlCommand command = conn.CreateCommand())
{
conn.Open();
string cmdText = String.Format("INSERT INTO UserFiles VALUES('" + obj.userRef.ToString() + "','name','name','name','name','name','name'");
command.CommandText = cmdText;
command.ExecuteNonQuery();
conn.Close();
}
}
以下是错误消息:
System.Data.SqlClient.Sqlexception(0x80131904):“name”附近得语法不正确。
在System.Data.SqlClient.SqlConnection.OnError(SqlException异常,Boolean breakConnection,Action1wrapCloseInAction)
1wrapCloseInAction)
在System.Data.SqlClient.SqlInternalConnection.OnError(SqlException异常,Boolean breakConnection,Action
在System.Data.SqlClient.Tdsparser.ThrowExceptionandWarning(TdsParserStateObject stateObj,C:\Users\Ken\Documents\GitHub\MegafileUploadConversionService\TestingTool\4900ProjectDesktopInterface\Form1.cs:行152\r\nClientConnectionID:FB95122F-415B-484D-9438-903F0BF2AAD0中的topInterface.form1.uploadButton_Click(对象发送者,EventArgs e)“
您的cmdtext
在末尾还需要一个)
;
using (SqlConnection conn = new SqlConnection(cs))
{
using (SqlCommand command = conn.CreateCommand())
{
conn.Open();
string cmdText = String.Format("INSERT INTO UserFiles VALUES(@userRef, @name1, @name2, @name3, @name4, @name5, @name6)");
command.Parameters.AddVithValue("@userRef", obj.userRef.ToString());
command.Parameters.AddVithValue("@name1", name);
command.Parameters.AddVithValue("@name2", name);
command.Parameters.AddVithValue("@name3", name);
command.Parameters.AddVithValue("@name4", name);
command.Parameters.AddVithValue("@name5", name);
command.Parameters.AddVithValue("@name6", name);
command.CommandText = cmdText;
command.ExecuteNonQuery();
conn.Close();
}
}
正如我在评论中所说的,您应该始终使用参数化查询。您的代码已为SQL注入攻击打开
using (SqlConnection conn = new SqlConnection(cs))
{
using (SqlCommand command = conn.CreateCommand())
{
conn.Open();
string cmdText = String.Format("INSERT INTO UserFiles VALUES('" + obj.userRef.ToString() + "','name','name','name','name','name','name')");
command.CommandText = cmdText;
command.ExecuteNonQuery();
conn.Close();
}
}
你忘了右括号
看起来您没有终止值的开放括号?为什么要使用String.Format?并且您可以删除conn.close,因为using语句将隐式地执行此操作。
using (SqlConnection conn = new SqlConnection(cs))
{
using (SqlCommand command = conn.CreateCommand())
{
conn.Open();
string cmdText = "INSERT INTO UserFiles VALUES('" + obj.userRef.ToString() + "','name','name','name','name','name','name')";
command.CommandText = cmdText;
command.ExecuteNonQuery();
}
}