【发布时间】:2017-03-24 20:33:27
【问题描述】:
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection cnn;
connetionString = "My_Connection";
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO person " +
"(name, lastname, phone) VALUES('@name', '@lastname', '@phone')");
cmd.CommandType = CommandType.Text;
cmd.Connection = cnn;
cmd.Parameters.AddWithValue("@name", txtName.Text);
cmd.Parameters.AddWithValue("@lastname", txtLastname.Text);
cmd.Parameters.AddWithValue("@phone", Convert.ToInt32(txtPhone.Text));
MessageBox.Show("Successful");
cnn.Close();
}
catch (SqlException ex)
{
MessageBox.Show("You failed!" + ex.Message);
}
}
【问题讨论】:
-
在这种情况下相当明显,但您应该明确说明您收到的错误消息是什么。如果您打算引用配置文件中的连接字符串,您也应该声明并显示相关的配置 sn-p。并花时间将您的代码格式化为正常的编码约定(删除所有额外的空格)。
-
你认为
connetionString = "MyConnection"会做什么? -
My_Connection应该是什么? -
"My_Connection"肯定是字符串,但它不是连接字符串。 -
您应该查看Can we stop using AddWithValue() already? 并停止使用
.AddWithValue()- 它可能会导致意想不到和令人惊讶的结果...
标签: c# sql-server