首先引入必要命名空間using System.Data;using System.Data.SqlClient;
在指定資料庫表中插入一條資料:
//將公告資訊插入資料庫中
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 + "','" + title + "','" + theNews + "',' " + author + "','" + starttime + "','" + latertime + "'," + theIndex + "," + theHeader + ")";
//更新資料庫時與插入資料庫語法基本上相同,但SQL語句不同
objConnection.Open();
SqlCommand objSqlCommand = new SqlCommand(strSql, objConnection);
objSqlCommand.ExecuteNonQuery();
}
catch (SqlException ex)
{ }
finally {
objConnection.Close();
}
查詢資料庫表信息,並遍歷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"; //查詢ID號碼最大的資訊記錄
objConnection.Open();
//SqlCommand objSqlCommand = new SqlCommand(strSql, objConnection);
//objSqlCommand.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(strSql,objConnection);
// 建立一個資料集物件並填入數據
DataSet ds = new DataSet("myTable");
da.Fill(ds, "myTable");
//操作DATASET將公告標題資訊擷取出來
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();
}
-