欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#實(shí)現(xiàn)連接SQL Server2012數(shù)據(jù)庫并執(zhí)行SQL語句的方法

 更新時間:2017年10月20日 10:41:27   作者:wz_微臣  
這篇文章主要介紹了C#實(shí)現(xiàn)連接SQL Server2012數(shù)據(jù)庫并執(zhí)行SQL語句的方法,結(jié)合實(shí)例形式較為詳細(xì)的分析了C#連接SQL Server2012數(shù)據(jù)庫并執(zhí)行查詢、插入等操作的相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下

本文實(shí)例講述了C#實(shí)現(xiàn)連接SQL Server2012數(shù)據(jù)庫并執(zhí)行SQL語句的方法。分享給大家供大家參考,具體如下:

開發(fā)工具:Visual Studio 2012
數(shù)據(jù)庫: SQL Server 2012

使用Visual Studio時還是直接和微軟自家的SQL Server數(shù)據(jù)庫連接比較方便,就像使用Eclipse時和MySQL連接便捷一樣的道理

無論使用什么工具步驟都一樣:

1. 首先保證相關(guān)工具都已經(jīng)正確安裝了
2. 開啟數(shù)據(jù)庫連接服務(wù)
3. 在開發(fā)工具中通過用戶名和口令與數(shù)據(jù)庫進(jìn)行關(guān)聯(lián)
4. 執(zhí)行SQL語句
5. 關(guān)閉相關(guān)連接和服務(wù)

連接數(shù)據(jù)庫

using System.Data.SqlClient;
SqlConnection conn = new SqlConnection();
string connectionString="server=.;database=Sql;uid=sa; pwd=123456";
conn.ConnectionString = connectionString;
conn.open();

server=.server=localhost是一樣的意思,都表示連接本地數(shù)據(jù)庫

database后跟數(shù)據(jù)庫的名稱

uidpwd就是你數(shù)據(jù)庫訪問時的用戶名和口令

到這里就可以查看一下數(shù)據(jù)庫連接的狀態(tài),可以直接將當(dāng)前連接的狀態(tài)輸出查看

Console.Write(conn.State.ToString());

如果執(zhí)行到這里發(fā)現(xiàn)有錯誤,就需要查看一下數(shù)據(jù)庫安裝的版本問題,打開SQL Server配置管理器

正常應(yīng)該是MSSQLSERVER,博主這里為了測試所以安裝了一個簡化版的SQLEXPRESS,如果你和博主的版本一樣就不能使用上面的連接數(shù)據(jù)庫的方式了

SqlConnectionStringBuilder scsb = new SqlConnectionStringBuilder();
scsb.DataSource = @"(local)\SQLExpress";
scsb.IntegratedSecurity = true;
scsb.InitialCatalog = sqlName;
SqlConnection conn = new SqlConnection(scsb.ConnectionString);
conn.open();

正確連接數(shù)據(jù)庫后,就可以執(zhí)行SQL語句了

string sqlStr = "SELECT * FROM table1";
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = sqlStr;
cmd.CommandType = CommandType.Text;
int i = Convert.ToInt32(cmd.ExecuteNonQuery());
Console.Write("共有" + i.ToString() + "條數(shù)據(jù)");
string sqlStr = "INSERT INTO table1 VALUES('1','a')";
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = sqlStr;
cmd.CommandType = CommandType.Text;
SqlDataReader dataReader = cmd.ExecuteReader();
if(dataReader.HasRows)
{
 while(dataReader.Read())
 {
  for(int i=0; i<dataReader.FieldCount; i++)
  {
   Console.Write(dataReader[i].ToString()+"\t");
  }
 }
}
int i = Convert.ToInt32(cmd.ExecuteNonQuery());
Console.Write("共有" + i.ToString() + "條數(shù)據(jù)");

最后別忘了關(guān)閉數(shù)據(jù)庫連接

conn.Close();

更多關(guān)于C#相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《C#常見數(shù)據(jù)庫操作技巧匯總》、《C#常見控件用法教程》、《C#窗體操作技巧匯總》、《C#數(shù)據(jù)結(jié)構(gòu)與算法教程》、《C#面向?qū)ο蟪绦蛟O(shè)計(jì)入門教程》及《C#程序設(shè)計(jì)之線程使用技巧總結(jié)

希望本文所述對大家C#程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評論