我想插入Unicode字母,我已经尝试将数据类型更改为nvarchar(max)
,我的select语句是
string str = "insert into Table1( (N'title), datee, post, cat, imageurl) values ('" + TextBox1.Text + "','" + DateTime.Now.ToShortDateString() + "','" + TextBox2.Text + "','" + DropDownList1.SelectedItem.Text + "','" + path+"')";`
答案 0 :(得分:5)
您应该始终使用参数化查询来避免SQL注入攻击。参数还使您能够明确定义数据类型以及所需的长度。此外,通过使用参数,您不需要使用大量的单引号和双引号等等 - 代码变得更清晰,更易于阅读 - 您也避免了很多错误!
尝试使用以下代码:
// define your INSERT statement with PARAMETERS
string insertStmt = "INSERT INTO dbo.Table1(title, datee, post, cat, imageurl) " +
"VALUES(@title, @datee, @post, @cat, @imageurl)";
// define connection and command
using(SqlConnection conn = new SqlConnection(yourConnectionStringHere))
using (SqlCommand cmd = new SqlCommand(insertStmt, conn))
{
// define parameters and set their values
cmd.Parameters.Add("@title", SqlDbType.NVarChar, 100).Value = TextBox1.Text.Trim();
cmd.Parameters.Add("@datee", SqlDbType.DateTime).Value = DateTime.Now;
cmd.Parameters.Add("@post", SqlDbType.NVarChar, 100).Value = TextBox2.Text.Trim();
cmd.Parameters.Add("@cat", SqlDbType.NVarChar, 100).Value = DropDownList1.SelectedItem.Text.Trim();
cmd.Parameters.Add("@imageurl", SqlDbType.NVarChar, 250).Value = path;
// open connection, execute query, close connection
conn.Open();
int rowsInserted = cmd.ExecuteNonQuery();
conn.Close();
}