How to fix "Invalid Column Name" SQL Exception on MSSQL - c#

I am trying to pass both Column name and the Value to be checked in the code at runtime. However I am getting an:
"Invalid Column Name "
Exception. The code is as follows :
cmd = new SqlCommand();
con.Open();
cmd.Connection = con;
cmd.CommandText = "INSERT INTO rezervasyon (Ad,Soyad,TelefonNo,OdaSayisi,KişiSayisi," +
"Ucret,Acıklama,GirisTarihi,CikisTarihi,KayitTarihi) VALUES " +
"(" + isim + ",'" + soyisim + "','" + telefon + "'," +
"'" + oda_sayisi + "','" + kisi_sayisi + "','" + ucret + "'," +
"'" + aciklama + "','" + giris_tar + "','" + cikis_tar + "'," +
"'" + current_tarih + "')";
cmd.ExecuteNonQuery();
con.Close();

You've missed a single quote here " + isim + " and it should be '" + isim + "'. However you should always use parameterized queries to avoid SQL Injection and also to get rid of this kind of errors.
cmd.CommandText = "INSERT INTO rezervasyon (Ad,Soyad,TelefonNo,OdaSayisi,KişiSayisi,Ucret" +
",Acıklama,GirisTarihi,CikisTarihi,KayitTarihi) " +
"VALUES (#isim, #soyisim , ...)";
cmd.Parameters.AddWithValue("#isim", isim);
cmd.Parameters.AddWithValue("#soyisim", soyisim);
//Other parameters
Although specify the type directly and use the Value property is more better than AddWithValue:
cmd.Parameters.Add("#isim", SqlDbType.VarChar).Value = isim;
Can we stop using AddWithValue() already?

Related

Inserting values into database multiple tables through C# windows application

private void btnsave_Click(object sender, EventArgs e)
{
string dbpath = #"Data Source=ABC;Initial Catalog=ApplicationForm;Integrated Security=True";
SqlConnection con = new SqlConnection(dbpath);
con.Open();
string savequerybscs="insert into bscs values('"+txtapplicantnumber.Text+"','"+txtname.Text+"','"+txtfathername.Text+"','"+txtmatrictotal.Text+"','"+txtmatricobtained.Text+"','"+txtmatricpercent.Text+"','"+txtintertotal.Text+"','"+txtinterobtained.Text+ "','"+txtinterpercent.Text+"')";
string savequerybsit ="insert into bsit values('" + txtapplicantnumber.Text + "','" + txtname.Text + "','" + txtfathername.Text + "','" + txtmatrictotal.Text + "','" + txtmatricobtained.Text + "','" + txtmatricpercent.Text + "','" + txtintertotal.Text + "','" + txtinterobtained.Text + "','" + txtinterpercent.Text + "')";
string savequerymcs ="insert into bscs values('" + txtapplicantnumber.Text + "','" + txtname.Text + "','" + txtfathername.Text + "','" + txtmatrictotal.Text + "','" + txtmatricobtained.Text + "','" + txtmatricpercent.Text + "','" + txtintertotal.Text + "','" + txtinterobtained.Text + "','" + txtinterpercent.Text + "','"+txtbachelortotal.Text+"','"+txtbachelorobtained.Text+"','"+txtbachelorpercent.Text+"')";
string savequerymit ="insert into bscs values('" + txtapplicantnumber.Text + "','" + txtname.Text + "','" + txtfathername.Text + "','" + txtmatrictotal.Text + "','" + txtmatricobtained.Text + "','" + txtmatricpercent.Text + "','" + txtintertotal.Text + "','" + txtinterobtained.Text + "','" + txtinterpercent.Text + "','" + txtbachelortotal.Text + "','" + txtbachelorobtained.Text + "','" + txtbachelorpercent.Text + "')";
SqlCommand cmd = new SqlCommand(savequerybscs,savequerymcs,bla blaa);
}
As you can see, this solution is pretty messed up. Is there any other way to handle such issues? All I want is to insert data in multiple tables simultaneously but SqlCommand only takes 1 argument.
I just learned about bulk query or bulk insertion. Can someone guide me through that? I am not clearly getting those concepts from youtube.
You can do one insert query using the comma separator between tuples for multiples rows:
insert into bsit values (field1, field2...), (field1, field2...), ...
But this insert is for one table.
Basically, you use as many SQL query as many table you want to update.
I'm not advanced but perhaps, depending on the database server, you could execute a "script" in one C# SqlCommand execute non query call, using the semilicon separator, like:
string sql = "insert into table1 values (field1, field2...), (field1, field2...), ... ; "
+ "insert into table2 values (field1, field2...), (field1, field2...), ... ;";
MySql should support that.
You should use SQL Parameters for security reason instead of adding values to the sql string itself:
string sql = "insert into table1 values (?, ?)";
var command = new OdbcCommand(sql, connection);
command.Parameters.Add("#ID", OdbcType.Text).Value = Guid.NewGuid().ToString();
command.Parameters.Add("#Name", OdbcType.Text).Value = "Test";
command.ExecuteNonQuery();
https://learn.microsoft.com/dotnet/api/system.data.sqlclient.sqlcommand.parameters

Problem with inserting unique value into SQL Server in C#

My code doesn't catch the exception when I try to add the same user to the database and I don't really know how to change it.
try
{
SqlConnection.Open();
string sqlZapytanie = "INSERT INTO Host Values('" + host.Name + "','" +
host.Surname + "'," + host.PESEL + ",'" + host.City + "','" + host.Street + "', '" + host.House_number + "','" + host.Apartament_number + "','" + host.e_mail + "'," + host.Phone_number + ",'"+host.Login+"')";
try
{
SqlCommand.Connection = SqlConnection;
SqlCommand.CommandText = sqlZapytanie;
SqlCommand.ExecuteNonQuery();
}
catch(SqlException sqlex)
{
MessageBox.Show(sqlex.Message, "Zduplikowany użytkownik.", MessageBoxButton.OK);
}
Perhaps the error to be returned is not type SqlException but type Exception.

Error in insert query in visual studio

I'm new in this field. Trying to insert the values from textbox to my database table, but I get an error at
adapter.InsertCommand.ExecuteNonQuery();
Can anyone help me solve this?
SqlCommand command;
SqlDataAdapter adapter = new SqlDataAdapter();
String sql = "insert into NewName values('" + first_Name.Text + "','" + last_Name.Text + "','" + user.Text + "','" + email.Text + "','" + password.Text + "','" + contact.Text + "')";
command = new SqlCommand(sql,con);
adapter.InsertCommand = new SqlCommand(sql,con);
// this line here is showing the error
adapter.InsertCommand.ExecuteNonQuery();
command.Dispose();
con.Close();
Since your table is called table and that is a SQL reserved word, you have two choices:
Change your table name. This is the only option you should be considering but for completeness;
Quote the name of the table:
insert into [table] values....
You do not list your column name on insert. This means you are also attempting to insert your identity column as well. Always list your column names
insert into NewName (firstname, lastname, username, email, password, contact)
values('" + first_Name.Text + "','" + last_Name.Text + "','" + user.Text + "','" + email.Text + "','" + password.Text + "','" + contact.Text + "')
Yes I've done it .I was using "user" in table column which is not allowed .After changing the column name everything works.
This is the code
SqlCommand command;
SqlDataAdapter adapter = new SqlDataAdapter();
String sql = "insert into NewName values('" + first_Name.Text + "','" + last_Name.Text + "','" + user.Text + "','" + email.Text + "','" + password.Text + "','" + contact.Text + "')";
command = new SqlCommand(sql, con);
adapter.InsertCommand = new SqlCommand(sql, con);
// this line here is showing the error
adapter.InsertCommand.ExecuteNonQuery();
command.Dispose();
con.Close();

How can i get result in two data table after execute the Query?

After execution result is coming in two select statement. How can get in two different data table by c#?
using (SqlConnection con = new SqlConnection(sqlConnString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "Exec SPSearchInvoiceList_rjt " + _customerID + "," + _ProjectInchargeID + "," + _projectID +
"," + _invoiceType + ",'" + _projectTypes + "'," + _invoiceAmount + ",'" + _invoiceCode +
"'," + _invoiceStatusID + ",'" + _invoiceDateFrom + "','" + _invoiceDateTo + "','" +
_invoiceRevisedDateFrom + "','" + _invoiceRevisedDateTo + "','" + _invoiceRaiseDateFrom +
"','" + _invoiceRaiseDateTo + "'," + Convert.ToInt32(PageIndex) + 1 + "," + pageSize;
cmd.Connection = con;
con.Open();
var datareader = cmd.ExecuteReader();
con.Close();
}
}
I am trying to do it as above.I am unable to get records but i am able to get data once i execute commandtext in sql server. Please help.

How to Converting SqlCommand Type To Int Type

I Want To Convert SqlCommand Result into Int Value How Can i Do that??
Please Help With That What I Have Tried IS Below:
The stp_no in Table Have Set Identity Property. And I want To insert That Auto Generated Numbers into Another Table But It Shows Always Error Like "Connot Convert SqlCommand Type to Int Type"
SqlCommand dvgcmd, snocmd;
snocmd = new SqlCommand("SELECT stp_no FROM MaterialTestMaster", con);
dvgcmd = new SqlCommand("INSERT INTO MaterialTestDetail(stp_no,test_no,test_name,test_type,test_spec,high_limit,low_limit)" +
"VALUES('"+ snocmd +"','" + #matTstDataGridView.Rows[j].Cells[0].Value + "'," +
" '" + #matTstDataGridView.Rows[j].Cells[1].Value + "'," +
" '" + #matTstDataGridView.Rows[j].Cells[2].Value + "'," +
" '" + #matTstDataGridView.Rows[j].Cells[3].Value + "'," +
" '" + #matTstDataGridView.Rows[j].Cells[4].Value + "'," +
" '" + #matTstDataGridView.Rows[j].Cells[5].Value + "')", con);
Please Help M to Solve This Problem :)
SqlCommand dvgcmd;
dvgcmd = new SqlCommand("INSERT INTO MaterialTestDetail(stp_no,test_no,test_name,test_type,test_spec,high_limit,low_limit)" +
"VALUES((SELECT stp_no FROM MaterialTestMaster),'" + #matTstDataGridView.Rows[j].Cells[0].Value + "'," +
" '" + #matTstDataGridView.Rows[j].Cells[1].Value + "'," +
" '" + #matTstDataGridView.Rows[j].Cells[2].Value + "'," +
" '" + #matTstDataGridView.Rows[j].Cells[3].Value + "'," +
" '" + #matTstDataGridView.Rows[j].Cells[4].Value + "'," +
" '" + #matTstDataGridView.Rows[j].Cells[5].Value + "')", con);
The answer of juergen should work, you have to execute first your command, then use the result as next:
int id = int.Parse(snocmd.ExecuteScalar().ToString());
dvgcmd = new SqlCommand("INSERT INTO MaterialTestDetail(stp_no,test_no,test_name,test_type,test_spec,high_limit,low_limit)" +
"VALUES('"+ id +"','" + #matTstDataGridView.Rows[j].Cells[0].Value + "'," +
" '" + #matTstDataGridView.Rows[j].Cells[1].Value + "'," +
" '" + #matTstDataGridView.Rows[j].Cells[2].Value + "'," +
" '" + #matTstDataGridView.Rows[j].Cells[3].Value + "'," +
" '" + #matTstDataGridView.Rows[j].Cells[4].Value + "'," +
" '" + #matTstDataGridView.Rows[j].Cells[5].Value + "')", con);

Categories