连接sql数据库:
private void Form1_Load(object sender, System.EventArgs e)
{
string source="server=127.0.0.1;"+"uid=sa;pwd=sa;"+"database=DatabaseName";
string select ="select * from TableName";
SqlConnection conn = new SqlConnection(source);
SqlDataAdapter da= new SqlDataAdapter(select,conn);
DataSet ds= new DataSet();
da.Fill(ds,"TableName");
dataGrid1.SetDataBinding(ds,"TableName");
}
************************************************************
连接access
string strConn= "Provider=Microsoft.Jet.OLEDB.4.0;"+"Password=;User ID=Admin;"+"data source=//127.0.0.1"+"inital catalog=student.mdb";
//string strConn="Provider = Microsoft.Jet.OLEDB.4.0; Data Source=27.0.0.1";
OleDbConnection myConn=new OleDbConnection(strConn);
myConn.Open();
string strInsert="INSERT INTO uuser(uuser,password,userid) VALUES(";
strInsert+=textBox1.Text+",'";
strInsert+=textBox2.Text+"''";
strInsert+=textBox3.Text+")";
OleDbCommand inst=new OleDbCommand(strInsert,myConn);
inst.ExecuteNonQuery();
myConn.Close();
*******************************************************
连接oracle
using System.Data.OleDb;
新建一个类(用于数据库连接的参数):
public static string GetOracleDbConnStr()
{
// 数据库连接
string tempUser="system",tempPassword="andystarmkmk",tempDataSource="andy";
string tempstrCon="Provider=OraOLEDB.Oracle.1;Persist Security Info=False;"+
"User ID="+tempUser+";Password="+tempPassword+";Data Source="+tempDataSource;
return tempstrCon;
}
设置Click事件:
private void button1_Click(object sender, System.EventArgs e)
{
string strSQL="select * from scott.aa";
string tempstrCon=Form1.GetOracleDbConnStr();
string tempstrCom="select * from scott.aa";
OleDbConnection tempmyConn=new OleDbConnection(tempstrCon);
DataSet tempmyDataSet=new DataSet();
OleDbDataAdapter tempmyCommand=new OleDbDataAdapter (tempstrCom,tempmyConn);
tempmyCommand.Fill(tempmyDataSet);
tempmyConn.Open();
dataGrid1.DataSource =tempmyDataSet;
OleDbCommand tempCommand=new OleDbCommand(strSQL,tempmyConn);
tempCommand.ExecuteNonQuery();
tempmyConn.Close();
}
注意:
1.连接数据库需要的参数:
◎OleDbConnection 用于建立连接
◎DataSet 数据在内存中的缓存,就是在内存中建立一个与数据库一致的表
◎OleDbDataAdapter 用于更新数据源
◎OleDbCommand 用于执行SQL命令
2.连接完成后应该马上关闭连接。