-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

3
  • 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? Commented Nov 27, 2020 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. Commented Nov 27, 2020 at 15:31
  • SQL Injection alert - you should not concatenate together your SQL statements - use parametrized queries instead to avoid SQL injection - check out Little Bobby Tables Commented Nov 27, 2020 at 17:20

1 Answer 1

-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 ' '

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.