Partha
Partha

Reputation: 21

Creating table at runtime and storing data in it

I want to create a table at the runtime and store information into it. Below the code which i tried.

SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True;");
con.Open();
String crt = "CREATE TABLE trail (Name Varchar(50) NOT NULL, Sex Varchar(50) NOT NULL)";
SqlCommand cov = new SqlCommand(crt, con);
cov.ExecuteReader();
String add = "Insert into trail value (@nam,@sex)";
SqlCommand cmd = new SqlCommand(add,con);
cmd.Parameters.AddWithValue("@nam",TextBox1.Text);
cmd.Parameters.AddWithValue("@sex", RbtGender.SelectedValue);
cmd.ExecuteReader();
con.Close();
Response.Redirect("Success.aspx");    

Upvotes: 0

Views: 244

Answers (2)

I wrote this code before cmd.Connection = con;

Then I wrote this cmd.ExecuteReader();

Upvotes: 0

Soner Gönül
Soner Gönül

Reputation: 98750

There is no point to use ExecuteReader with CREATE statement. It does not return any data anyway (and it retursn SqlDataReader, it is not a void method). Use ExecuteNonQuery instead to execute your queries. Same with INSERT statement also.

And it is values not value. Take a look at INSERT (Transact-SQL) syntax.

Also use using statement to dispose your SqlConnection and SqlCommand like;

using(SqlConnection con = new SqlConnection(connString))
using(SqlCommand cov = con.CreateCommand())
{
   //
}

Don't use AddWithValue by the way. Use one of Add overloads. This method has some problems.

Read: http://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/

Upvotes: 1

Related Questions