我无法在表格中插入数据 [英] I can't insert data in table

查看:103
本文介绍了我无法在表格中插入数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

protected void Submit_Click(object sender, EventArgs e)
{
    SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS; database= Registration; trusted_connection=yes");
    conn.Open();
    
    SqlCommand com = new SqlCommand("insert into register(Username, password, email id, first name) values(" + TextBoxUS.Text + "," + TextBoxPass.Text + "," + TextBoxEA.Text + "," + TextBoxFN.Text + ") ", conn);

    com.ExecuteNonQuery();
}



很抱歉,发帖之前
该错误显示为未处理SqlException"
错误在此行= com.ExecuteNonQuery();



I am sorry for before post
The error its showing as "SqlException was unhandled "
The error is in this line= com.ExecuteNonQuery(); it showing "Incorrect syntax near ''id''."

推荐答案

列名称中不能包含空格,如果必须这样做,则必须在其两边加上方括号.

例如:电子邮件ID-> [电子邮件ID]
Column names cannot have spaces in them if they do you must put brackets around them.

For example : email id -> [email id]


还有另一件事.切勿直接将值连接到SQL语句.这使您容易受到SQL注入,数据类型转换问题等的影响.相反,请始终使用 SqlParameter [
And another thing. Never concatenate values directly to your SQL statements. This leaves you vulnerable to SQL injections, data type conversion problems and so on. Instead, always use SqlParameter[^]

So your query could look something like
...
SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS; database= Registration; trusted_connection=yes");
conn.Open();
    
SqlCommand com = new SqlCommand("insert into register(Username, password, [email id], [first name]) values(@username, @password, @emailid, @firstname) ", conn);

com.Parameters.AddWithValue("@username", TextBoxUS.Text);
com.Parameters.AddWithValue("@password", TextBoxPass.Text);
com.Parameters.AddWithValue("@emailid", TextBoxEA.Text);
com.Parameters.AddWithValue("@firstname", TextBoxFN.Text);

com.ExecuteNonQuery();
...


不要在列名之间使用空格.在[[电子邮件ID]]括号中使用列名,而不要使用电子邮件ID.

如果列名中有空格,则SQL读取为不同的列名.电子邮件,另一个是ID.
don`t use space between column name. Use column name in bracket Like [email id] instead of email id.

if space in column name then SQL read as different column name. email and another one is id.


这篇关于我无法在表格中插入数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆