C#连接数据库方式,Access,SQL Server,Oracle,MySQL,IBM DB2 ,SyBase,excel等,[bubufx分享asp.net基础]
现在的业务系统都离不开数据库,编程语言与数据库连接是最基本的asp.net学习基础,所以,先弄清楚了C#链接数据库,工作才真正开始。最常用的数据库就是微软的Access和SQL Server,Oracle在工作中也常用到,MySQL在讲究版权的公司里也会出现,IBM DB2 ,SyBase相对稀罕。
asp.net中支持的语言很多,最最常用的也就是C#了,vb.net也常见,基本上是熟悉vb的一直在延续着。
1、连接Access数据库
Access数据库的链接需要引用“System.Data.OleDb”命名空间。先看一个示例:
using System;
using System.Collections.Generic;
using System.Web;
using System.Text;
using System.Data;
using System.Data.OleDb;
namespace code
{
class DB
{
public string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + System.Web.HttpContext.Current.Server.MapPath("/_dt/bubufx.mdb");
public DataTable GetDt(string sql)
{
DataSet ds = new DataSet();
OleDbConnection conn = new OleDbConnection(connStr);
if (conn.State == ConnectionState.Closed) conn.Open();
OleDbDataAdapter da = new OleDbDataAdapter(sql, conn);
da.Fill(ds);
conn.Close();
return ds.Tables[0];
}
public int RunSql(string sql)
{
try
{
OleDbConnection conn = new OleDbConnection(connStr);
if (conn.State == ConnectionState.Closed) conn.Open();
OleDbCommand comm = new OleDbCommand(sql, conn);
comm.ExecuteNonQuery(); conn.Close();
return 1;
}
catch { return 0; }
}
}
}
这是一个链接access的类,直接使用也可。调用“GetDt”可运行select等返回datatable,调用“RunSql”可直接运行insert、update、delete等语句。链接字符串是"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + System.Web.HttpContext.Current.Server.MapPath("/_dt/bubufx.mdb"),在页面中就不必“System.Web.HttpContext.Current.Server.MapPath("/_dt/bubufx.mdb")”这么长,直接Server.MapPath("/_dt/bubufx.mdb")即可。
各种版本的access链接字符串并不相同:
Access 2000:“provider=Microsoft.Jet.Oledb.3.5;Data Source=Access数据库文件路径”
Access 2003:“provider=Microsoft.Jet.Oledb.4.0;Data Source=Access数据库文件路径”
Access 2007:“provider=Microsoft.Ace.Oledb.12.0;Data Source=Access数据库文件路径”
Access数据库只提供两个连接属性provider(数据提供程序)和data source(数据源);
Access2000\2003的文件格式是“。mdb”,Access2007的文件格式是“。accdb”;
Access的数据提供程序版本是向下兼容的,在Win7下测试使用Microsoft.Jet.OLEDB.3.5提示“未在本地计算机上注册“Microsoft.Jet.OLEDB.3.5”提供程序。”,改用Microsoft.Jet.OLEDB.4.0或者Microsoft.Ace.OLEDB12.0完全可以访问Access2000的数据库文件。当然也可以尝试使用微软提供的MDAC 来修改provider的版本。
2、连接SQL Server数据库
SQL Server数据库的链接需要用到“System.Data.SqlClient”命名空间,先看一个示例:
using System;
using System.Collections.Generic;
using System.Web;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
public class DB
{
public DB()
{
}
public int RunSQL(string inSQL)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
SqlCommand sqlCmd = new SqlCommand(inSQL, conn);
try
{
conn.Open();
sqlCmd.CommandTimeout = 600;
sqlCmd.ExecuteNonQuery();
return 1;
}
catch
{
return 0;
}
finally
{
sqlCmd.Dispose();
conn.Close();
conn.Dispose();
}
}
public DataTable GetDt(string inSQL)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
SqlDataAdapter sqlDA = new SqlDataAdapter(inSQL, conn);
DataTable outDt = new DataTable();
conn.Open();
sqlDA.SelectCommand.CommandTimeout = 600;
sqlDA.Fill(outDt);
sqlDA.Dispose();
conn.Close();
conn.Dispose();
return outDt;
}
}
以上是封装好的类库,可以直接声明变量调用方法执行sql语句。上例中数据库链接字符串是放在web.congfig中的,如:
<connectionStrings>
<add name="ConnString" connectionString="Password=bubufx123;Persist Security Info=True;User ID=sa;Initial Catalog=bubufx;Data Source=.\SQLSERVER2008" />
</connectionStrings>
a、SQL Server验证模式连接
"Server=服务器名;Database=数据库名称;User ID=用户;User Password=密码;"使用缩写与别名“Server=服务器名;Initial Catalog=数据库名称;Uid=用户;Pwd=密码;”
b、数据库文件完整路径(SQLEXPRESS)
“Server=(local)\SQLEXPRESS; AttachDbFilename=D:\\bubufx\\bubufxTech\\App_Data\\bubufx.mdf;User Password=bubufx123”
c、Windows 验证模式连接
“Server=服务器名;Database=数据库名称;Integrated Security=SSPI;Server=(local)\SQLEXPRESS;”
数据库文件完整路径:“Serve=服务器名;AttachDbFilename=数据库文件路径; Integrated Security=true”
3、连接Oracle
一下C#连接Oracle代码,仅供参考
using System.Data.OracleClient;
using System.Data;
...
string connString="Data Source=bubufxServer;user=system;password=bubufx123;";//写连接串
OracleConnection conn=new OracleConnection(connString);//创建一个新连接
try
{
conn.Open();
OracleCommand comd=conn.CreateCommand();
comd.CommandText="select * from bubufxTable";
OracleDataReader odr=comd.ExecuteReader();
while(odr.Read())
{
Response.Write(odr.GetOracleString(1).ToString());
}
odr.Close();
}
catch(Exception bubufxEX)
{
Response.Write(bubufxEX.Message);
}
finally
{
conn.Close();
}
4、连接MySQL
using MySQLDriverCS;
MySQLConnection DBConn;
DBConn = new MySQLConnection(new
MySQLConnectionString("localhost","mysql","root","",3306).AsString);
DBConn.Open();
MySQLCommand DBComm;
DBComm = new MySQLCommand("select a,b from bubufxTable",DBConn);
MySQLDataReader DBReader = DBComm.ExecuteReaderEx();
try
{
while (DBReader.Read())
{
Console.WriteLine("Host =
{0} and User = {1}", DBReader.GetString(0),DBReader.GetString(1));
}
}
finally
{
DBReader.Close();
DBConn.Close();
}
DBConn.Close();
5、连接IBM DB2
OleDbConnection1.Open(); OleDbDataAdapter1.Fill(dataSet1,"bubufx"); DataGrid1.DataBind(); OleDbConnection1.Close(); this.OleDbInsertCommand1.CommandText = "INSERTsintosADDRESS(NAME, EMAIL, AGE, ADDRESS) VALUES (’bubufx1’,’bubufx2’,’bubufx3’,’bubufx4’)"; OleDbInsertCommand1.Connection.Open(); OleDbInsertCommand1.ExecuteNonQuery(); OleDbInsertCommand1.Connection.Close();6、连接SyBase
Provider=Sybase.ASEOLEDBProvider.2;Initial Catalog=数据库名;User ID=用户名;Data Source=数据源;Extended Properties="";Server Name=ip地址;Network Protocol=Winsock;Server Port Address=5000;
7、连接excel
C#连接excel类似access,只要将相应连接字符串换成连接excel的就可以将excel当作数据库来读取了。
97-2003版本:
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=文件位置;Extended Properties=Excel 8.0;HDR=Yes;IMEX=1
2007版本:
Provider=Microsoft.Ace.OleDb.12.0;Data Source=文件位置;Extended Properties=Excel 12.0;HDR=Yes;IMEX=1
备注:【其他说明】
HDR=Yes/NO 表示是否将首行做标题。
IMEX 表示是否强制转换为文本
特别提示:
Extended Properties=’Excel 8.0;HDR=yes;IMEX=1’
A: HDR ( HeaDer Row )设置
若指定值为Yes,代表 Excel 档中的工作表第一行是栏位名称
若指定值為 No,代表 Excel 档中的工作表第一行就是資料了,沒有栏位名称
B:IMEX ( IMport EXport mode )设置
IMEX 有三种模式,各自引起的读写行为也不同,容後再述:
0 is Export mode
1 is Import mode
2 is Linked mode (full update capabilities)
我这里特别要说明的就是 IMEX 参数了,因为不同的模式代表著不同的读写行为:
当 IMEX=0 时为“汇出模式”,这个模式开启的 Excel 档案只能用来做“写入”用途。
当 IMEX=1 时为“汇入模式”,这个模式开启的 Excel 档案只能用来做“读取”用途。
当 IMEX=2 时为“连結模式”,这个模式开启的 Excel 档案可同时支援“读取”与“写入”用途。
示例参考:
private DataTable getexcelDT(string excelPath)
{
FileInfo fi = new FileInfo(excelPath);
string strCon = @" Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = " + excelPath + ";Extended Properties=Excel 8.0";
OleDbConnection myConn = new OleDbConnection(strCon);
string strCom = " SELECT * FROM [" + fi.Name.Replace(".xls", "") + "$] ";
myConn.Open();
OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myConn);
DataSet ds = new DataSet();
myCommand.Fill(ds, "[" + fi.Name.Replace(".xls", "") + "$]");
myConn.Close();
return ds.Tables[0];
}