Dzeko
Dzeko

Reputation: 27

How to execute SQL command using ADO.NET in C#?

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

Upvotes: -3

Views: 1413

Answers (1)

zakaria daoudi
zakaria daoudi

Reputation: 13

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

Upvotes: -1

Related Questions