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"
What is the proper way to do that ?
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.
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.
Basic ADO.NET 101:
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With