我刚刚开始研究c#.net。下面是我的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class Default2 : System.Web.UI.Page
{
//SqlConnection con = new SqlConnection("Data Source=ADMIN-PC\\SQLEXPRESS;Initial Catalog=register;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
}
private const string strconneciton = "Data Source=ADMIN-PC\\SQLEXPRESS;Initial Catalog=register;Integrated Security=True";
SqlConnection con = new SqlConnection(strconneciton);
protected void Button1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand("insert into user(uname, address,
email, number) values('" + TextBox1.Text + "', '" + TextBox2.Text + "', '" +
TextBox3.Text + "', '" +TextBox4.Text+ "')", con);
cmd.ExecuteNonQuery();
con.Close();
}
}
我收到此错误
'System.Data.dll'中出现'System.Data.SqlClient.SqlException'类型的异常,但未在用户代码中处理
请帮忙。我正在使用microsoft sql server management studio。
答案 0 :(得分:2)
不要硬编码 sql查询:
number
是MS Sql的保留字并且应该作为[number]
)TextBox2.Text
包含 apostroph ,'
)我建议提取一种方法:
private void CoreInsert() {
//Done: wrap IDisposable into using, do not close explicitly
//TODO: do not hardcode strConnection, but read from settings
using (SqlConnection con = new SqlConnection(strConnection)) {
con.Open();
// Make sql
// 1. Readable: can you see a problem with "Number" now?
// 2. Parametrized
string sql =
@"insert into [user](
uname,
address,
email,
[number]) -- <- number is MS SQL's reserved word, put it as [number]
values(
@prm_uname,
@prm_address,
@prm_email,
@prm_number)";
//Done: wrap IDisposable into using
using (SqlCommand cmd = new SqlCommand(sql, con)) {
cmd.Parameters.AddWithValue("@prm_uname", TextBox1.Text);
cmd.Parameters.AddWithValue("@prm_address", TextBox2.Text);
cmd.Parameters.AddWithValue("@prm_email", TextBox3.Text);
//TODO: check actual field's type here
cmd.Parameters.AddWithValue("@prm_number", TextBox4.Text);
cmd.ExecuteNonQuery();
}
}
}
然后调用方法
protected void Button1_Click(object sender, EventArgs e) {
CoreInsert();
}
答案 1 :(得分:0)
使用Parameters函数始终为命令字符串添加值。我认为你的问题是你发送值“number”作为char,你可以在你的数据库中将它定义为int。因此,您可以尝试从Textbox4.Text
删除单个qutoes。
但是如果你想让它更好,请使用参数。就像那样。
SqlCommand cmd = new SqlCommand("insert into user(uname, address,
email, number) values(@uname,@address,@email,@number)", con);
cmd.Parameters.AddWithValue("@uname", TextBox1.Text);
cmd.Parameters.AddWithValue("@address", TextBox2.Text);
cmd.Parameters.AddWithValue("@email", TextBox3.Text);
cmd.Parameters.AddWithValue("@number", TextBox4.Text);
cmd.ExecuteNonQuery();
这也可以防止任何SQL注入问题。