Hi Mark,
depending on what type of DB you are using the answer can be a little bit
different. By SQL Database do you mean Microsoft SQL Server?
In the example below I will assume a SQL Server DB. If you are not you
will need to swap SqlConnection for a OleDbConnection etc.
1. The first thing you need to know is the connection string to connect to
the DB. The connection sting contains things like the server name, database
name, user name, password etc (username and password might not always be
there depending on which security model you choose). A good place to find
the string you need is
www.connectionstrings.com it shows examples for
different types of DBs. For example a SQL Server connection string could be:
string connectionString = "Server=Aron1;Database=pubs;User
ID=sa;Password=asdasd;Trusted_Connection=False";
2. Next in .Net you need to create a Connection object to connect to the DB,
for SQL server this will be a System.Data.SqlClient.SqlConnection:
SqlConnection connection = new SqlConnection(connectionString);
3. Next you have to say what type of SQL command are you going to use a
Stored procedure or a text expression i.e. "SELECT * FROM tblX". LEt's
assume you don't have any stored procedures (ideally you would), you need to
create a SqlCommand object:
SqlCommand command = new SqlCommand();
command.CommandType = CommandType.Text;
command.CommandText = "INSERT INTO tblData(a,b,c) VALUES(1,2,3)";
command.Connection = connection;
4. Open the connection and execute the command, the ExecuteNonQuery() method
indicates we don't expect any data coming back (unlike if we had done a
SELECT)
connection.Open();
command.ExecuteNonQuery();
5. An important thing to do is to clean up after you have finished, you
don't want to leave open database connection lying around, so we want to
close the connection, you should always put your code inside a try{}
finally{} block with the connection.Close() inside the finally. An
alternative is to put it inside a using statement which will call Dispose
inside a finally behind the scenes which in turn calls Close. So you end up
with something like:
string connectionString = "Server=Aron1;Database=pubs;User
ID=sa;Password=asdasd;Trusted_Connection=False";
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand())
{
command.CommandType = CommandType.Text;
command.CommandText = "INSERT INTO tblData(a,b) VALUES(1,2)";
command.Connection = connection;
connection.Open();
command.ExecuteNonQuery();
}
There are lots of excellent resources out there to look at, just search
google or look at the Microsoft help for SqlConnection etc and you will find
all you need.
Hope that helps
Mark R Dawson
http://www.markdawson.org