所以我一直收到这个错误。我不确定问题是否出在 SQL 服务器中。此代码用于将数据插入数据库。
发送帮助。
I'm getting this message while executing the code
private void registracija_btn_Click(object sender, EventArgs e)
{
string RegistracijaUporabnisko = RegistracijaUporabnisko_txt.Text;
string RegistracijaGeslo = RegistracijaGeslo_txt.Text;
string RegistracijaMail = RegistracijaMail_txt.Text;
try
{
string queryReg = "INSERT INTO uporabnik2(uporabnisko_ime, geslo, email) " +
"VALUES(" + RegistracijaUporabnisko + ", " + RegistracijaGeslo + ", " + RegistracijaMail + ")";
using (SqlCommand command = new SqlCommand(queryReg, con))
{
con.Open();
command.ExecuteNonQuery();
con.Close();
}
}
catch (Exception ex)
{
MessageBox.Show("Napaka: " + ex);
}
}
最佳答案
让我们看看您的代码:
string queryReg = "INSERT INTO uporabnik2(uporabnisko_ime, geslo, email) " +
"VALUES(" + RegistracijaUporabnisko + ", " + RegistracijaGeslo + ", " + RegistracijaMail + ")";
using (SqlCommand command = new SqlCommand(queryReg, con))
{
con.Open();
command.ExecuteNonQuery();
con.Close();
}
好的,如果 RegistracijaUporabnisko
的值为 Rok,RegistracijaGeslo
的值为 Rok,RegistracijaMail
的值为 Rok@home.. 你的字符串是什么现在的样子?嗯
string queryReg = "INSERT INTO uporabnik2(uporabnisko_ime, geslo, email) VALUES(Rok,Rok,Rok@home)";
它要查找的 Rok 是一个字段,而不是一个值。因此它说无效列。
如果你采用一种常用的方式来实现
string queryReg = "INSERT INTO uporabnik2(uporabnisko_ime, geslo, email) VALUES(@RegistracijaUporabnisko ,@RegistracijaGeslo ,@email)";
using (SqlCommand command = new SqlCommand(queryReg, con))
{
command.Parameters.AddWithValue("@RegistracijaUporabnisko ", RegistracijaUporabnisko );
command.Parameters.AddWithValue("@RegistracijaGeslo ", RegistracijaGeslo );
command.Parameters.AddWithValue("@email", email);
con.Open();
command.ExecuteNonQuery();
con.Close();
}
现在会发生什么?好吧,在幕后输入文本并在其周围加上引号,以适当的格式发送日期,为您处理所有的数字。它可以保护您免受注入(inject),因此如果我输入名称 "; drop table uporabnik2
您不会发现自己丢失了表等。
关于c# - System.Data.SqlClient.SqlException : Invalid column name (Error at line command. ExecuteNonQuery();),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54666087/