-3

First of all, I passed the connection string to SqlConnection as parameter:

SqlConnection con = new SqlConnection("server=ZIKO_RED2486;database=Students;Integrated Security = true"); 

Then I open that connection:

con.Open();

and I also created the query string:

string query = "INSERT INTO Students VALUES ('"+txt_id.Text+"','"+txt_fname.Text+"','"+txt_sname.Text+"','"+txt_numberP+"','"+txt_age.Text +"')";

Then I passed it as parameter with the connection inside SqlCommand + execute it + close the connection :

    SqlCommand cmd = new SqlCommand(query, con);
    cmd.ExecuteNonQuery();
    con.Close();

But when I run the app, I get an exception:

System.Data.SqlClient.SqlException: 'Invalid object name'

I created the table Students with five columns (id, f_name, s_name, number_p, age) before all of that.

Thanks for your help in advance

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Dzeko
  • 27
  • 6
  • so to clear things up , databases can't have column! databases contain tables and tables have columns , so are you sure you have a table called "Students" in your database? – eshirvana Nov 27 '20 at 15:22
  • 3
    I'd recommend that you look into using sql parameters, first to avoid sql injection and second so you don't have to determine when you do or do not need single quotes around the values. Second you really should list out the column names like `Insert Into Table(Col1, Col2) Values(@Col1, @Col2)` to make sure the values match up with the columns you want to put them into. – juharr Nov 27 '20 at 15:31
  • [SQL Injection alert](http://msdn.microsoft.com/en-us/library/ms161953%28v=sql.105%29.aspx) - you should **not** concatenate together your SQL statements - use **parametrized queries** instead to avoid SQL injection - check out [Little Bobby Tables](http://bobby-tables.com/) – marc_s Nov 27 '20 at 17:20

1 Answers1

-1
string query = "INSERT INTO Students VALUES
 ("+txt_id.Text+",'"+txt_fname.Text+"','"+txt_sname.Text+"','"+txt_numberP.Text+"','"+txt_age.Text +"')";

try this query !

I think you declare id as int primary key so we don't put id between quotes ' '

KETAN PATIL
  • 2,276
  • 2
  • 13
  • 18