我正在尝试向我的数据库发送此查询,它一直让我无效输入,我不知道出了什么问题?
private void button1_Click(object sender, EventArgs e)
{
string connectionString =@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True";
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(
"INSERT INTO Customer(Name,Telephone,Address,[Register Date]) VALUES(" + v_name + "," + telephone + "," + address + "," + date + ")", connection))
{
try
{
connection.Open();
string result = (string)command.ExecuteScalar();
MessageBox.Show("Region = " + result);
MessageBox.Show("You have Registered Succesfully");
}
catch(Exception ex)
{
MessageBox.Show("Invalid input");
Form1 st = new Form1();
st.Show();
}
}
}
}
答案 0 :(得分:1)
我没有看到你的连接有什么问题,但我发现如何执行你的命令有问题。
ExecuteScalar
返回第一列第一行的数据。但是您的INSERT
语句不会返回任何数据。您需要改为使用ExecuteNonQuery
。
你应该总是使用parameterized queries。这种字符串连接对SQL Injection攻击开放。
using(SqlConnection connection = new SqlConnection(connectionString))
using(SqlCommand command = connection.CreateCommand())
{
cmd.CommandText = @"INSERT INTO Customer(Name,Telephone,Address,[Register Date])
VALUES(@name, @tel, @address, @date)";
// Add your parameter values with SqlParameterCollection.Add() method.
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch(Exception ex)
{
//
}
}
答案 1 :(得分:0)
我认为错误在你的qry中。 如果db字段是nvarchar,那么你应该传递''之间的值。 你的qry如下:
"INSERT INTO Customer(Name,Telephone,Address,[Register Date]) VALUES('" + v_name + "','" + telephone + "','" + address + "','" + date + "')"