3

我想插入我已经尝试将数据类型更改为的 Unicode 字母,nvarchar(max)并且我的选择语句是

string str = "insert into Table1( (N'title), datee, post, cat, imageurl) values  ('" + TextBox1.Text + "','" + DateTime.Now.ToShortDateString() + "','" + TextBox2.Text + "','" + DropDownList1.SelectedItem.Text + "','" + path+"')";`
4

1 回答 1

5

You should always use parametrized queries to avoid SQL injection attacks. Parameters also give you the ability to explicitly define what data types and which length you want. Furthermore, by using parameters, you don't need to fiddle with lots of single and double quotes and so forth - the code becomes much cleaner and easier to read - and you avoid a lot of errors, too!

Try code something like this:

// 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();
}
于 2013-05-12T16:30:07.067 回答