473,396 Members | 2,013 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

How do you insert a DataTable into a Database?

13
ok i'm new to this whole .net scene so i have been battling trying to find examples on how to add a newly created table into the database (connection)?
Here's what i have so far!


//create table
DataTable table = new DataTable("MyTable");
table.Columns.Add(new DataColumn("Name", Type.GetType("System.String")));
table.Columns.Add(new DataColumn("Age", Type.GetType("System.Byte")));

//add a row of data
DataRow dataRow = table.NewRow();
dataRow["Name"] = "John";
dataRow["Age"] = 30;
table.Rows.Add(dataRow);

//?????????????????????????
.
.
(Here's where i'm stuck)
How do I add my table above to the db connection below?
.
.
//?????????????????????????

//create database connection
OleDbConnection dbConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + DBFULLNAME);

------------------------------------------------------


sorry i know their must be an example somewhere but have been searching for hours with no luck at all!

thanks for any help.
Jan 11 '08 #1
13 6480
camel
55
If you are asking how to get data into SQL Server that is held in a DataTable the answer would be associate an Adapter or Command to DataTable and Update.

If you are asking how to add a physical Table to a SQL Server Database you would use SMO\SQLDMO or straight TSQL, not ADO. You could also use an OleDb connection to define a new table but it would not have any data in it.
Jan 11 '08 #2
horizon
13
If you are asking how to get data into SQL Server that is held in a DataTable the answer would be associate an Adapter or Command to DataTable and Update.

If you are asking how to add a physical Table to a SQL Server Database you would use SMO\SQLDMO or straight TSQL, not ADO. You could also use an OleDb connection to define a new table but it would not have any data in it.
Well if my above example didn't show you where i'm stuck, then i'm at a loss?

All i'm after is the missing link between my DataSet and DBConnection! I've already created the database i just need to insert the damn table into it.

I looked into the DataAdapter which will allow me to supply a DataSet that the DataTable i'm using contains, but that still doesn't bring me any closer to inserting the table?

any help would be appreciated.
Jan 11 '08 #3
horizon
13
ok it appears no one understands my problem? i'll try to explain further.

1) i created a new empty database in my project folder, using SQLConfigDataSource (win32 api)

2) now i'd like to insert a new table using my example above in my first post, which uses "DataSet", "DataTable", "DataColumn" and "DataRow"


I can achieve that using the following code: (but i'd much rather learn how to use the above code)

---------------------
OleDbConnection dbConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\mydb.mdb");
dbConn.Open();

OleDbCommand cmd = new OleDbCommand();
cmd.Connection = dbConn;

// create table
cmd.CommandText = "CREATE TABLE mytable (Name VARCHAR(25), Age INTEGER)";
cmd.ExecuteNonQuery();

//add a row of data
cmd.CommandText = "INSERT INTO mytable VALUES ('John', 30)";
cmd.ExecuteNonQuery();

dbConn.Close();
---------------------

but what's the use of having all those previous classes if i can't insert the final table into the database????


i'm sure there's a way and it's probably just a couple of lines of code but i just haven't found the right class to do it, and i'm sick of google!, if anyone could help i would really apreciate it.
Jan 11 '08 #4
Plater
7,872 Expert 4TB
You created the database. Great.
The question was, does the table exist in the database?

The use of those precious classes is immense, and once you get the hang of it, they're great.
You are creating a DataTable object and filling it with data.
As stated, if the table already exists in the database (will make it much easier) you can associate a simple SQL insert statement for it.

If the table does NOT exist in the database, and you want to create it at runtime, there is a lot of work to do.
You need to check to see if it's there. DROP (sql command) the table, CREATE TABLE (sql command) and THEN you can add data to it.

However, if you just want to create the table beforehand, go into your database software and create the table in there. Then you can use the simple INSERT (sql command) with your DataTable object as mentioned above.
Jan 11 '08 #5
horizon
13
You created the database. Great.
The question was, does the table exist in the database?
NO, i already stated it's a new EMPTY database.
The use of those precious classes is immense, and once you get the hang of it, they're great.
well that's what i'm trying to achieve here, and without much success so far.
You are creating a DataTable object and filling it with data.
As stated, if the table already exists in the database (will make it much easier) you can associate a simple SQL insert statement for it.
i already said i'm creating it at runtime using the following:

[DllImport("ODBCCP32.dll")]
private static extern bool SQLConfigDataSource(IntPtr hwndParent, ODBC fRequest, string lpszDriver, string lpszAttributes);

If the table does NOT exist in the database, and you want to create it at runtime, there is a lot of work to do.
You need to check to see if it's there. DROP (sql command) the table, CREATE TABLE (sql command) and THEN you can add data to it.
again, this is not what i'm asking - i can check that myself (thanks for your concern)
However, if you just want to create the table beforehand, go into your database software and create the table in there. Then you can use the simple INSERT (sql command) with your DataTable object as mentioned above.
everyone seems to keep dodging my question? i could understand if this was top-secret, but where talking about inserting a silly populated DataSet into a new empty (WITH NO TABLES) database!

it seems like there is no answer here (let alone an small example), anyway thanks again plater for your time but since i can't get a straight answer i think i'll just keep searching elsewhere (what a nightmare should of stuck with c++!!!).
Jan 11 '08 #6
Plater
7,872 Expert 4TB
Certainly not top secret.
http://www.google.com/search?source=...=Google+Search
Jan 11 '08 #7
Lokean
71
Certainly not top secret.
http://www.google.com/search?source=...=Google+Search
and at least on google he won't get hit with snarky answers to his queries
Jan 11 '08 #8
Plater
7,872 Expert 4TB
I'm sure if you look on google long enough you will find snarky answers :-)

Snarky questions lead to snarky answers.
Jan 11 '08 #9
camel
55
Gosh this thread got carried away after what I thought was an intial "cover either question" answer ! I had to look up "snarky", not a word I would associate with.

The simple answer I believe was provided at the outset but obviously not explained clearly. You cannot create a database table directly from an ADO DataTable or DataSet, that is not the purpose of these objects which are by definition for manipulating data not defining schema. If you wish to use managed code to create a database object, table or otherwise, without using any SQL statements in the code, the use either SQL Server Management Objects (SMO), Data Management Objects (DMO) or OleDb schema objects.
Jan 12 '08 #10
camel
55
I should of course have given DMO its proper name SQLDMO, which stands for Distributed Management Objects or Database Management Objects. Anyway in .Net with SQL Server 2005 you have SMO so don't need SQLDMO.

In short the reason you can't find the answer you are looking for is the answer is "no", it makes sense to separate the classes that manipulate data from those that manipulate structure and that is what Microsoft have done.
Jan 12 '08 #11
horizon
13
(ignoring the post's above camel's)...

thank's camel for clearly explaining that i was on the wrong path even if i may of got a tad hot-headed on my last post, but that's the toll from searching long hours for a solution that never existed, btw i did finally figure that out towards the end but won't take any credit from you! thanks again and sorry for all the confusion, just wish someone would have told me sooner but no one's to blame except my inexperience.

ps: hey camel i also had to search that word, all i can say is urbandictionary(dot)com has a nice page layout :-)
Jan 12 '08 #12
ok i'm new to this whole .net scene so i have been battling trying to find examples on how to add a newly created table into the database (connection)?
Here's what i have so far!


//create table
DataTable table = new DataTable("MyTable");
table.Columns.Add(new DataColumn("Name", Type.GetType("System.String")));
table.Columns.Add(new DataColumn("Age", Type.GetType("System.Byte")));

//add a row of data
DataRow dataRow = table.NewRow();
dataRow["Name"] = "John";
dataRow["Age"] = 30;
table.Rows.Add(dataRow);

//?????????????????????????
.
.
(Here's where i'm stuck)
How do I add my table above to the db connection below?
.
.
//?????????????????????????

//create database connection
OleDbConnection dbConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + DBFULLNAME);

------------------------------------------------------


sorry i know their must be an example somewhere but have been searching for hours with no luck at all!

thanks for any help.


u want that code in C# or vb
Jan 12 '08 #13
Well if my above example didn't show you where i'm stuck, then i'm at a loss?

All i'm after is the missing link between my DataSet and DBConnection! I've already created the database i just need to insert the damn table into it.

I looked into the DataAdapter which will allow me to supply a DataSet that the DataTable i'm using contains, but that still doesn't bring me any closer to inserting the table?

any help would be appreciated.
Expand|Select|Wrap|Line Numbers
  1. public partial class _Default : System.Web.UI.Page 
  2. {
  3.     string conn = "server=balaji;database=harish;uid=sa;pwd=sqlserver";
  4.  
  5.     //this method for geting  selectedindexvalues for dropdownlist through sqldatasource for 
  6.     //displaying the gridview
  7.     protected void DDLnames_SelectedIndexChanged(object sender, EventArgs e)
  8.     {
  9.         SqlConnection scon = new SqlConnection(conn);
  10.         SqlDataAdapter sda = new SqlDataAdapter("select * from tbl_names where stu_name='" + DDLnames.SelectedItem.Text.ToString() + "'", scon);
  11.         DataSet ds = new DataSet();
  12.         sda.Fill(ds, "tbl_names");
  13.         GridView1.DataSource = ds;
  14.         GridView1.DataBind();
  15.     }
  16.  
  17.     //normal function
  18.     public void FillCustomerInGrid()
  19.     {
  20.         SqlConnection sconn = new SqlConnection(conn);
  21.         // SqlDataAdapter sda = new SqlDataAdapter("select * from tbl_names where stu_name='" + DDLnames.SelectedItem.Text.ToString() + "'", sconn);
  22.         SqlDataAdapter sda = new SqlDataAdapter("select * from tbl_names", sconn);
  23.         DataSet ds = new DataSet();
  24.         sda.Fill(ds, "tbl_names");
  25.         GridView1.DataSource = ds.Tables["tbl_names"];
  26.         GridView1.DataBind();
  27.     }
  28.     //update function
  29.     public void updatCustomerInGrid()
  30.     {
  31.         SqlConnection sconn = new SqlConnection(conn);
  32.        // SqlDataAdapter sda = new SqlDataAdapter("select * from tbl_names where stu_name='" + DDLnames.SelectedItem.Text.ToString() + "'", sconn);
  33.         SqlDataAdapter sda = new SqlDataAdapter("select * from tbl_names", sconn);
  34.         DataSet ds = new DataSet();
  35.         sda.Fill(ds, "tbl_names");
  36.         GridView1.DataSource =ds.Tables["tbl_names"];
  37.         GridView1.DataBind();
  38.         Response.Write("<script>alert('updated')</script>");
  39.  
  40.  
  41.     }
  42.     //edit function
  43.     public void editCustomerInGrid()
  44.     {
  45.         SqlConnection sconn = new SqlConnection(conn);
  46.         SqlDataAdapter sda = new SqlDataAdapter("select * from tbl_names where stu_name='" + DDLnames.SelectedItem.Text.ToString() + "'", conn);
  47.         //SqlDataAdapter sda = new SqlDataAdapter("select * from tbl_names", sconn);
  48.         DataSet ds = new DataSet();
  49.         sda.Fill(ds, "tbl_names");
  50.         GridView1.DataSource = ds.Tables["tbl_names"];
  51.         GridView1.DataBind();
  52.      }
  53.     //cancle function
  54.     public void cancelCustomerInGrid()
  55.     {
  56.         //creation of conncetion object 
  57.         SqlConnection sconn = new SqlConnection(conn);
  58.         SqlDataAdapter sda = new SqlDataAdapter("select * from tbl_names where stu_name='" + DDLnames.SelectedItem.Text.ToString() + "'", sconn);
  59.         DataSet ds = new DataSet();
  60.         sda.Fill(ds, "tbl_names");
  61.         GridView1.Rows[0].Cells.Clear(); 
  62.         //GridView1.DataSource = ds.Tables["tbl_names"];
  63.         GridView1.DataBind();
  64.      }
  65.  
  66.  
  67.  
  68.     protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
  69.     {
  70.         //to get editindex values
  71.         GridView1.EditIndex = e.NewEditIndex;
  72.         editCustomerInGrid();
  73.     }
  74.     protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
  75.     {
  76.         //creation of textbox objects
  77.         TextBox txtnum = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtnum");
  78.         TextBox txtnames = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtnames");
  79.         TextBox txtbranch = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtbranch");
  80.         TextBox txtupdate = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtupdate");
  81.         if(txtnum=)
  82.         {
  83.         //creating  upadting command 
  84.         string upcommand = "UPDATE tbl_names SET stu_num=" + txtnum.Text + ",stu_name='" + txtnames.Text + "',stu_branch='" + txtbranch.Text + "'WHERE stu_num=" + txtnum.Text +"";
  85.         SqlConnection sconn = new SqlConnection(conn);
  86.         sconn.Open();
  87.         SqlCommand scmd = new SqlCommand(upcommand, sconn);  
  88.         //give the which type of the command it is query or storedprocs
  89.         scmd.CommandType = CommandType.Text;
  90.         scmd.ExecuteNonQuery();
  91.         sconn.Close();
  92.         GridView1.EditIndex = -1;//index value
  93.         updatCustomerInGrid();
  94.  
  95.         }
  96.         }
  97.     protected void Page_Load(object sender, EventArgs e)
  98.     {
  99.         //displaying the gridview 
  100.  
  101.         //SqlConnection sconn = new SqlConnection(conn);
  102.         //SqlDataAdapter sda = new SqlDataAdapter("select * from tbl_names", sconn);
  103.         //DataSet ds = new DataSet();
  104.         //sda.Fill(ds, "tbl_names");
  105.         //GridView1.DataSource = ds.Tables["tbl_names"];
  106.         //GridView1.DataBind();
  107.  
  108.     }
  109.  
Jan 12 '08 #14

Sign in to post your reply or Sign up for a free account.

Similar topics

5
by: Necqui Teja | last post by:
Is there a quick and effcient way to insert records into SQL Server database from a DataTable (DataTable dt;) when the DataTable and the SQL Server database contain the same field names and...
1
by: Dazz | last post by:
Hello I have made a small app to query a database which works fine. I am now adding a logging function which writes back to the database in a separate table. When I update the OleDataAdapter,...
3
by: Ed | last post by:
Hi, I want to load data to a table in Sql Server from a dataset table in my vb.net app using a dataAdapter. I know how to do this as follows (my question is to see if I can reduce the amount...
1
by: Scott Emick | last post by:
I have the following datatables which are related: Transaction TransactionId-Sequence Orders OrderDetails when I process a daTransaction.update(dtTransaction)...
6
by: Marcel Hug | last post by:
Hi all ! I have a table in my database, which has 3 attributes. IDFailureControl, ControlDate and ControlVersion. In the following function I test, if the date of today allready exists. Then I...
5
by: Brad Baker | last post by:
I'm trying to write a simple asp.net page which updates some data in a SQL database. At the top of the page I have the following code: <%@ Page Language="C#" Debug="true" %> <%@ import...
3
by: John Cosmas | last post by:
I have a DATATABLE which I have populated in my application, and I need it written out to a particular table I specify in my ACCESS database. My code works to the point of the MERGE and UPDATE,...
3
by: iKiLL | last post by:
Hi all I am having problems getting my SqlCeDataAdapter to Update the SQL Mobile Data base. i am using C# CF2. I have tried this a number of different ways. Starting with the command builder...
2
by: krajah | last post by:
Need Help Here....... I'm using visual C#: How to insert the value that user have entered combobox and click button.The value will sent into database.This is in form1. In form2,if click button...
7
by: Matt | last post by:
So as you all know the great thing about ADO.NET is that I can take an entire table from a database and dump it into an in memory datatable using ADO.NET. Well my question is that now that I...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.