c#连接各种数据库的方法

2 [C#] 200 连接数据库方法收集  
"Connect Timeout=30":连接超时时间为30秒.
在这里,建立连接对象用的构造函数为:SqlConnection.
--------------------------------------------------------------------------------

3.C#连接Oracle
程序代码:
--------------------------------------------------------------------------------

using System.Data.OracleClient;
using System.Data;

//在窗体上添加一个按钮,叫Button1,双击Button1,输入以下代码
private
void Button1_Click(object sender, System.EventArgs e)

{
string ConnectionString="Data Source=sky;user=system;password=manager;";//写连接串
OracleConnection conn=new OracleConnection(ConnectionString);//创建一个新连接
try

{
conn.Open();
OracleCommand cmd=conn.CreateCommand();

cmd.CommandText="select * from MyTable";//在这儿写sql语句
OracleDataReader odr=cmd.ExecuteReader();//创建一个OracleDateReader对象
while(odr.Read())//读取数据,如果odr.Read()返回为false的话,就说明到记录集的尾部了

{
Response.Write(odr.GetOracleString(1).ToString());//输出字段1,这个数是字段索引,具体怎么使用字段名还有待研究
}
odr.Close();
}
catch(Exception ee)

{
Response.Write(ee.Message); //如果有错误,输出错误信息
}
finally

{
conn.Close(); //关闭连接
}
}

-------------------------------------------------------------------------------

4.C#连接MySQL
程序代码:
--------------------------------------------------------------------------------
using MySQLDriverCS;

// 建立数据库连接
MySQLConnection DBConn;
DBConn =
new MySQLConnection(new MySQLConnectionString("localhost","mysql","root","",3306).AsString);
DBConn.Open();

// 执行查询语句
MySQLCommand DBComm;
DBComm =
new MySQLCommand("select Host,User from user",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.C#连接IBM DB2
程序代码:
--------------------------------------------------------------------------------
OleDbConnection1.Open();
//打开数据库连接
OleDbDataAdapter1.Fill(dataSet1,"Address");
//将得来的数据填入dataSet
DataGrid1.DataBind();
//绑定数据
OleDbConnection1.Close();
//关闭连接

//增加数据库数据
在Web Form上新增对应字段数量个数的TextBox,及一个button,为该按键增加Click响应事件代码如下:

this.OleDbInsertCommand1.CommandText =
"INSERTsintosADDRESS(NAME,
EMAIL, AGE, ADDRESS) VALUES
('"+TextBox1.Text+"','"+TextBox2.Text+"','"+TextBox3.Text+"','"+TextBox4.Text+"')";
OleDbInsertCommand1.Connection.Open();
//打开连接
OleDbInsertCommand1.ExecuteNonQuery();
//执行该SQL语句
OleDbInsertCommand1.Connection.Close();
//关闭连接

--------------------------------------------------------------------------------

6.C#连接SyBase
程序代码: (OleDb)
--------------------------------------------------------------------------------

Provider=Sybase.ASEOLEDBProvider.2;Initial Catalog=数据库名;User ID=用户名;Data Source=数据源;Extended Properties="";Server Name=ip地址;Network Protocol=Winsock;Server Port Address=5000;

 

posted @ 2011-11-16 10:28  指尖流淌  阅读(1021)  评论(0编辑  收藏  举报