Core ADO.NET 101:
- establish a connection
- configure the command to execute
- execute this command
Step 1: setup the connection
You need to know the connection string to your database. See http://www.connectionstrings.com for tons of examples.
In your case, you say that this is a local instance of SQL Server Express, but, unfortunately, you did not specify what your database is called ..... your connection string will look something like this:
server=(local)\SQLEXPRESS;database=YourDatabaseName;user id=database;pwd=testdatabase
Step 2: setting up the team
You can have different commands - selecting data, deleting it, or inserting data. Whatever you do, I would recommend always using parameterized queries to avoid SQL injection.
So your code looks something like this:
string connectionString = "server=(local)\SQLEXPRESS;database=YourDatabaseName;user id=database;pwd=testdatabase"; string insertStmt = "INSERT INTO dbo.Laptops(Name, Model, ScreenSize) " + "VALUES(@Name, @Model, @Screensize)"; using(SqlConnection conn = new SqlConnection(connectionString)) using(SqlCommand cmd = new SqlCommand(insertStmt, conn)) { // set up the command parameters cmd.Parameters.Add("@Name", SqlDbType.VarChar, 100).Value = "ASUS SX30"; cmd.Parameters.Add("@Model", SqlDbType.VarChar, 50).Value = "Ultralight"; cmd.Parameters.Add("@Screensize", SqlDbType.Int).Value = 15; // open connection, execute command, close connection conn.Open(); int result = cmd.ExecuteNonQuery(); conn.Close(); }
source share