C#數(shù)據(jù)庫操作的示例詳解
功能需求
1,利用隨機數(shù)模擬產(chǎn)生每次考試成績
2,將每次考試成績存入到數(shù)據(jù)庫
3,將每次考試成績劃分優(yōu)、良、中、差、不及格五類,并作為查詢條件,查詢符合每種水平的成績
技術(shù)知識點
1.random類的使用
2.數(shù)據(jù)庫的鏈接、添加數(shù)據(jù)、查詢數(shù)據(jù)、讀取數(shù)據(jù)
3,combox控件的使用
4,DataGridView控件的使用
準備工作
創(chuàng)建數(shù)據(jù)庫,本文案例使用Sql Server2014,數(shù)據(jù)庫表如下:

實現(xiàn)步驟
1.模擬產(chǎn)生考試成績,點擊考試按鈕,產(chǎn)生六科考試成績
Random rd = new Random();//實例化random類
int[] scores = new int[6];
for(int i = 0;i<scores.Length;i++)
{
scores[i] = rd.Next(0, 100);
SumScore += scores[i];//總成績
}
AvgScore = SumScore / scores.Length;//平均分
ScoreLevel = GetScoreLevel(SumScore);
tbx01.Text = scores[0].ToString();
tbx02.Text = scores[1].ToString();
tbx03.Text = scores[2].ToString();
tbx04.Text = scores[3].ToString();
tbx05.Text = scores[4].ToString();
tbx06.Text = scores[5].ToString();
2.將每次考試成績存儲到數(shù)據(jù)庫中,通過按鈕觸發(fā)。
//創(chuàng)建數(shù)據(jù)庫操作類,DBOpera,方便其他功能在進行數(shù)據(jù)庫操作時,減少重復(fù)工作。
//數(shù)據(jù)庫鏈接字符串,使用private防止為外部訪問修改
private static string connstring = @"Data source = RANDOM\SQLEXPRESS; Initial Catalog = DB1;User ID=sa; pwd = 123456";
//數(shù)據(jù)庫鏈接對象
public static SqlConnection conn = new SqlConnection(connstring);
//定義執(zhí)行sql查詢語句方法
public int ExecSQL(string sql)
{
//執(zhí)行查詢語句后并不需要返回所有的查詢結(jié)果,而僅需要返回一個值,
//例如查詢表中的記錄行數(shù)
//實例化sqlcommand類。
SqlCommand cmd = new SqlCommand(sql, conn);
if (conn.State == ConnectionState.Closed)//如果當前數(shù)據(jù)庫鏈接處于關(guān)閉狀態(tài)
conn.Open();
int num = Convert.ToInt32(cmd.ExecuteScalar());//執(zhí)行查詢
conn.Close();
return num;
}
public int ExecSQLResult(string sql)
{
/*執(zhí)行非查詢 SQL 語句時并不需要返回表中的數(shù)據(jù)
增加、修改、刪除的操作
該方法的返回值是一個整數(shù),表示 SqlCommand 類在執(zhí)行 SQL 語句后,
對表中數(shù)據(jù)影響的行數(shù)。返回值為-1時,代表 SQL 語句執(zhí)行失敗,返回值為 0 時,代表 SQL 語句對當前數(shù)據(jù)表中的數(shù)據(jù)沒有影響。*/
//實例化sqlcommand對象
SqlCommand cmd = new SqlCommand(sql, conn);
if (conn.State == ConnectionState.Closed)
conn.Open();
int result = cmd.ExecuteNonQuery();
conn.Close();
return result;
}
public DataSet GetDataSet(string sql)
{
//將數(shù)據(jù)表中的數(shù)據(jù)查詢出來并添加到 DataSet 中
//每個 DataSet 都是由若干個數(shù)據(jù)表構(gòu)成的,DataTable 即數(shù)據(jù)表,
//每個 DataTable 也都是由行和列構(gòu)成的,
//行使用 DataRow 類表示、列使用 DataColumn 類表示。
SqlDataAdapter sqlda = new SqlDataAdapter(sql, conn);
DataSet ds = new DataSet();
sqlda.Fill(ds); //填充數(shù)據(jù)集
return ds; // 返回數(shù)據(jù)集
}
public SqlDataReader GetDataReader(string sql)
{
//讀取表中的查詢結(jié)果,以只讀方式讀取的(即不能修改 DataReader 中存放的數(shù)據(jù))
//當查詢結(jié)果僅為一條時,可以使用 if 語句查詢 DataReader 對象中的數(shù)據(jù),
//如果返回值是多條數(shù)據(jù),需要通過 while 語句遍歷 DataReader 對象中的數(shù)據(jù)。
SqlCommand cmd = new SqlCommand(sql, conn);
if (conn.State == ConnectionState.Closed)
conn.Open();
SqlDataReader sqlDR = cmd.ExecuteReader();
return sqlDR;
}
}
//外部調(diào)用DBOpera類,將模擬產(chǎn)生的考試成績存儲到數(shù)據(jù)庫中
//將考試成績保存到數(shù)據(jù)庫中
//調(diào)用DataOperaor類中ExecSQLResult方法
string sql = "insert into MScore(Level,Math,Chinese,English," +
"Chemical,Physics,Biology,TotalScore,AvgScore) values" +
"('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}')";
//填充SQL語句
sql = string.Format(sql, ScoreLevel, tbx01.Text, tbx02.Text, tbx03.Text, tbx04.Text, tbx05.Text,
tbx06.Text, SumScore.ToString(), AvgScore.ToString());
int result = DbOpera.ExecSQLResult(sql);
if (result != -1)
{
MessageBox.Show("數(shù)據(jù)存儲成功");
}
else
{
MessageBox.Show("數(shù)據(jù)存儲失?。?);
}
3.利用組合框,顯示所有考試成績的評語
//創(chuàng)建方法,判斷成績的評語
public static string GetScoreLevel(int score)
{
string level = null;
//總分540-600為優(yōu),480-540為良,420-480為中,360-420為差,低于420為不及格
if(score >= 540)
{
level = "優(yōu)";
}
else if(score >= 480)
{
level = "良";
}
else if (score >= 420)
{
level = "中";
}
else if (score >= 360)
{
level = "差";
}
else
{
level = "不及格";
}
return level;
}
//從數(shù)據(jù)庫讀取每次考試成績評語,并將數(shù)據(jù)顯示到組合框中
//查詢考試成績所處分段,并將這些信息在組合框中顯示
//定時查詢語句
//cbx01為控件combox名稱
ArrayList arylist = new ArrayList();
string sql = "select distinct level from MScore";
DataSet ds = DbOpera.GetDataSet(sql);
if(ds.Tables[0].Rows.Count >0)
{
DataTable dt = ds.Tables[0];
foreach (DataRow dr in dt.Rows)
{
arylist.Add(dr[0].ToString().Trim());
}
cbx01.DataSource = arylist;
}
4.根據(jù)查詢條件,查詢符合條件的數(shù)據(jù),并使用DataGridView控件顯示
private void button3_Click(object sender, EventArgs e)
{
//查詢考試總成績大于查詢值的成績分布數(shù)據(jù)
//定義查詢語句
string sql = "select Math,Chinese,English,Chemical,Physics,BIology,TotalScore,AvgScore from mscore where level ='" + cbx01.Text.ToString().Trim()+"'";
//創(chuàng)建DataSet類的對象
//datagridview1為控件datagridview名稱
DataSet ds = DbOpera.GetDataSet(sql);
dataGridView1.DataSource = ds.Tables[0];
dataGridView1.Columns[0].HeaderText = "數(shù)學(xué)";
dataGridView1.Columns[1].HeaderText = "語文";
dataGridView1.Columns[2].HeaderText = "英語";
dataGridView1.Columns[3].HeaderText = "化學(xué)";
dataGridView1.Columns[4].HeaderText = "物理";
dataGridView1.Columns[5].HeaderText = "生物";
dataGridView1.Columns[6].HeaderText = "總分";
dataGridView1.Columns[7].HeaderText = "平均分";
// 設(shè)置數(shù)據(jù)表格為只讀
dataGridView1.ReadOnly = true;
//不允許添加行
dataGridView1.AllowUserToAddRows = false;
//背景為白色
dataGridView1.BackgroundColor = Color.White;
//只允許選中單行
dataGridView1.MultiSelect = false;
//整行選中
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
}
動畫演示效果

以上就是C#數(shù)據(jù)庫操作的示例詳解的詳細內(nèi)容,更多關(guān)于C#數(shù)據(jù)庫操作的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C# OleDbDataReader快速數(shù)據(jù)讀取方式(3種)
這篇文章主要介紹了C# OleDbDataReader快速數(shù)據(jù)讀取方式(3種),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12

