0912 ADO.NET 增刪改查

來源:互聯網
上載者:User

標籤:

1.使用c#對資料庫進行增刪改基本上一致(以改為例)

Console.Write("請輸入要修改的學號:");
string a = Console.ReadLine();
Console.Write("請輸入修改後的姓名:");
string b = Console.ReadLine();
Console.Write("請輸入修改後的性別:");
string c = Console.ReadLine();
Console.Write("請輸入修改後的生日:");
string d = Console.ReadLine();
Console.Write("請輸入修改後的民族:");
string e = Console.ReadLine();

1.串連資料庫

//串連資料庫                                             伺服器名稱          資料庫名稱          登入使用者名稱    登入密碼
SqlConnection conn = new SqlConnection("server=(local);database=Ado0720;user=sa;pwd=123456;");

四個部分必須仔細,而且必須寫對.

2.

//對資料庫進行操作

SqlCommand cmd = conn.CreateCommand();

//動作陳述式,跟資料庫中操作類似(在這是修改)

cmd.CommandText = "update renyuan set name=‘"+b+"‘,sex=‘"+c+"‘,birthday=‘"+(DateTime.Parse(d))+"‘,nation=‘"+e+"‘ where code=‘"+a+"‘";

//執行開始
conn.Open();
cmd.ExecuteNonQuery();
//執行結束
conn.Close();

//提示一下

Console.WriteLine("修改成功!");

Console.ReadLine();

2.查   比上面三個稍微複雜一點

//串連資料庫
SqlConnection conn = new SqlConnection("server=.;database=Ado0720;user=sa;pwd=123456;");
//對資料庫進行操作
SqlCommand cmd = conn.CreateCommand();
//動作陳述式
cmd.CommandText = "select*from renyuan";
//執行操作
conn.Open();
//將資料拿到記憶體中
SqlDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
//列印的兩種方法
//使用索引號
//Console.Write(dr[0]+"    "+dr[1]+"    "+dr[2]+"    "+dr[3]+"    "+dr[4]);
//使用列名
Console.Write(dr["code"] + "    " + dr["name"] + "    " + dr["sex"] + "    " +((Convert.ToDateTime(dr["birthday"])).ToString("yyyy年MM月dd日")) + "    "

+ dr["nation"]+"\t");
Console.WriteLine();
}                  
conn.Close();         
           
Console.ReadLine();

0912 ADO.NET 增刪改查

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.