Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to make a connection and query to a SQL Server Express database

I need a sample C# (console application) code witch connects to an SQL Server Express database and inserts a few variables into a table "laptops"

  • SQL Server Express is @ localhost
  • user name is database
  • and password is testdatabase

What is the proper way to do that ?

like image 262
Axxess Avatar asked Feb 19 '12 09:02

Axxess


People also ask

How do I create a database connection in SQL Server?

On the Tools menu, click Data Connections. In the Data Connections dialog box, click Add. In the Data Connection Wizard, click Create a new connection to, click Receive data, and then click Next. On the next page of the wizard, click Database (Microsoft SQL Server or Microsoft Office Access only), and then click Next.

How do I remotely connect to SQL Express database?

Open SQL Server Management Studio (SSMS) Go to the Security page for Server Authentication, and select 'SQL Server and Windows Authentication' mode. Then, go to the Connections page and ensure that "Allow remote connections to this server" is checked, and click OK.


1 Answers

Basic ADO.NET 101:

  • set up a connection
  • set up a command to do something
  • execute that command

Step 1: setting up a connection

You need to know the connection string to your database. Check out http://www.connectionstrings.com for a ton of examples.

In your case, you say it's a local SQL Server Express instance - but unfortunately, you didn't mention what your database is called..... your connection string will be something like:

server=(local)\SQLEXPRESS;database=YourDatabaseName;user id=database;pwd=testdatabase

Step 2: setting up a command

You can have various commands - to select data, to delete that, or to insert data. Whatever you do - I would recommend to always use parametrized queries to avoid SQL injection.

So your code here would look something like:

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's 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();
}
like image 164
marc_s Avatar answered Nov 14 '22 22:11

marc_s