我已经搜索了该论坛,并尝试了许多可能的解决方案,但没有任何效果。任何人都可以阐明这种情况吗?谢谢!
SqlConnection con = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=TESTdatabase;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand(
"INSERT into tblGenerator (GeneratorName, GeneratorAddress, GeneratorCity, GeneratorState, GeneratorZip, GeneratorPhone, GeneratorContact, GeneratorEPAID) " +
"VALUES ('" + GenName.Text + "' , '" + GenAdd.Text + "' , '" + GenCity.Text + "' , '" + GenState.Text + "' , '" + GenZip.Text + "' , '" + GenPhone.Text + "' ," +
" '" + GenContact.Text + "' , '" + GenEPAID.Text + "' ), con");
cmd.ExecuteNonQuery();
con.Close();
答案 0 :(得分:0)
看起来在创建SqlCommand时,连接已作为Insert语句的一部分。具体来说,“,con”仍包裹在您的文本字符串中。如果将最后一个双引号移到括号后,它将起作用。
但是,我建议像这样重写您的代码:
using (var con = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=TESTdatabase;Integrated Security=True"))
{
if(ConnectionState.Closed == con.State) con.Open();
using (var cmd = con.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = $@"INSERT INTO tblGenerator (GeneratorName, GeneratorAddress, GeneratorCity, GeneratorState, GeneratorZip, GeneratorPhone, GeneratorContact, GeneratorEPAID)
VALUES ('{GenName.Text}', '{GenAdd.Text}', '{GenCity.Text}', '{GenState.Text}', '{GenZip.Text}', '{GenPhone.Text}', '{GenContact.Text}', '{GenEPAID.Text}')";
cmd.ExecuteNonQuery();
}
}
答案 1 :(得分:0)
这是我最终使用的代码。感谢大家的帮助。
SqlConnection myConnection =
new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=TESTdatabase;Integrated Security=True");
SqlCommand myCommand = new SqlCommand(
"INSERT into tblGenerator (GeneratorName, GeneratorAddress, GeneratorCity, GeneratorState, GeneratorZip, GeneratorPhone, GeneratorContact, GeneratorEPAID)" +
"VALUES (@GenName, @GenAdd, @GenCity, @GenState, @GenZip, @GenPhone, @GenContact, @GenEPAID)");
myCommand.Parameters.AddWithValue("@GenName", GenName.Text);
myCommand.Parameters.AddWithValue("@GenAdd", GenAdd.Text);
myCommand.Parameters.AddWithValue("@GenCity", GenCity.Text);
myCommand.Parameters.AddWithValue("@GenState", GenState.Text);
myCommand.Parameters.AddWithValue("@GenZip", GenZip.Text);
myCommand.Parameters.AddWithValue("@GenPhone", GenPhone.Text);
myCommand.Parameters.AddWithValue("@GenContact", GenContact.Text);
myCommand.Parameters.AddWithValue("@GenEPAID", GenEPAID.Text);
myConnection.Open();
myCommand.Connection = myConnection;
MessageBox.Show("You Have Successfully Added a New Generator To SQL");
myCommand.ExecuteNonQuery();
myConnection.Close();