First introduce the necessary namespace using System.Data;using System.Data.SqlClient;
Insert a piece of data into the specified database table:
//Insert announcement information into the database
SqlConnection objConnection = null;
try
{
string strConnection = "Data Source=192.168.0.10;Initial Catalog=e_comm;Persist Security Info=True;
UserID=sa;Password=symsunsymsun123";
objConnection = new SqlConnection(strConnection);
string strSql;
strSql = "insert into [e_comm].[dbo].[newsHistory](NEWSTITLE,THENEWS,THEAUTHOR,THESTARTDATE,THELATERDATE,VIEWINDEX,THEHEADER) values('" + title + "','" + theNews + "',' " + author + "','" + starttime + "','" + latertime + "'," + theIndex + "," + theHeader + ")";
//The syntax when updating the database is basically the same as inserting into the database, except that the SQL statements are different.
objConnection.Open();
SqlCommand objSqlCommand = new SqlCommand(strSql, objConnection);
objSqlCommand.ExecuteNonQuery();
}
catch (SqlException ex)
{ }
finally {
objConnection.Close();
}
Query database table information and traverse DATASET:
SqlConnection objConnection = null;
try
{
string strConnection = "Data Source=192.168.0.10;Initial Catalog=e_comm;Persist Security Info=True;User ID=sa;Password=symsunsymsun123";
objConnection = new SqlConnection(strConnection);
string strSql;
strSql = "select top 1 * from [e_comm].[dbo].[newsHistory] order by NEWSID DESC"; //Query the information record with the largest ID number
objConnection.Open();
//SqlCommand objSqlCommand = new SqlCommand(strSql, objConnection);
//objSqlCommand.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(strSql,objConnection);
//Create a dataset object and fill it with data
DataSet ds = new DataSet("myTable");
da.Fill(ds, "myTable");
//Operate DATASET to extract the announcement title information
if (ds.Tables["myTable"].Rows.Count > 0)
{
foreach (DataTable dt in ds.Tables)
{
foreach (DataRow dr in dt.Rows)
{
theLastedItem = dr["NEWSTITLE"].ToString() + " " + dr["THESTARTDATE"].ToString();
theLastedId = dr["NEWSID"].ToString();
}
}
}
}
catch (SqlException ex)
{ }
finally
{
objConnection.Close();
}
-