C# - Simple SQL command

Here are some simple code in C# if you want to select data from your database.
Product
IdProductNameDescription


DataTable dataTable = new DataTable();
string connStr = "Data Source=MachineName\SQLEXPRESS;Initial Catalog=DatabaseName;Integrated Security=True";
string query = "select Id, ProductName, Description from Product";
using (SqlConnection conn = new SqlConnection(connStr))
{
    SqlDataAdapter da = new SqlDataAdapter(query, conn);
    da.Fill(dataTable);
}

foreach (DataRow row in dataTable.Rows)
{
    Console.WriteLine(row["Id"].ToString(), row["ProductName"].ToString(), row["Description"].ToString());
    ....
}

Data Source is the name of the database server. Initial Catalog is the database name. If you set the Integrated Security to true, it will used the Windows account of the current process to login to the server. In case the user id and password is different from the windows account, use this

string connStr = "Data Source=MachineName\SQLEXPRESS;Initial Catalog=DatabaseName;User ID=username;Password=yourPassword";



You can also use SqlCommand to read data from the database. For other SQL command like insert, delete and update, I'm not sure if there is other way beside using SqlCommand.

using (SqlConnection conn = new SqlConnection(connStr))
{
    SqlCommand dataCommand = new SqlCommand();
    dataCommand.Connection = conn;
    dataCommand.CommandText = "update Product set ProductName='NewProductName' where Id='30'";

    conn.Open();
    int x = dataCommand.ExecuteNonQuery();
    conn.Close();
}

0 comments:

Post a Comment

top