none
Can not create table in DataSet and Update to the database RRS feed

  • Question

  •            SqlConnection con = new SqlConnection("server=.;database=ashutosh2;user id=sa;password=."); 
                con.Open(); 
                SqlDataAdapter da = new SqlDataAdapter("select * from emp", con); 
     
                SqlCommandBuilder scb = new SqlCommandBuilder(da); 
     
                DataSet ds = new DataSet("emp"); 
                da.Fill(ds, "emp"); 
     
                DataTable dt = new DataTable("MyTable"); 
                dt.Columns.Add("empno"typeof(int)); 
                dt.Columns.Add("ename"typeof(string)); 
                ds.Tables.Add(dt); 
                 
                DataRow dr = ds.Tables["MyTable"].NewRow(); 
                dr["empno"] = 4; 
                dr["ename"] = "ashutosh"
                ds.Tables["MyTable"].Rows.Add(dr); 
     
                da.Update(ds, "MyTable"); 
                con.Close(); 

    Actually i want to create a table in a DataSet and when call the update method it should create table in the database. Can it be done ?
    • Moved by VMazurModerator Friday, March 6, 2009 11:08 AM (Moved from ADO.NET Data Providers to ADO.NET DataSet)
    Thursday, March 5, 2009 5:56 PM

Answers

  • Just creating DataTable in your DataSet will NOT create any table in database. You need to create table first using database designer or using CREATE TABLE statement. DataSets are abstracted from any specific database and have no idea about how to create any database objects. If it is common task for you, you could prepare CREATE TABLE ... statement in your code and execute it using ExecuteNonQuery method of SqlCommand. But also keep in mind that creating table in database most likely will require administrator permissions, which means if you do it from your code, users potentially could create any kind of table even if they should not, and have unrestricted access to other information that might be secure


    Val Mazur (MVP) http://www.xporttools.net
    Friday, March 6, 2009 11:06 AM
    Moderator