c#数据库连接代码
///系统引用
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.Container components = null;
private System.Data.DataSet myDataSet;
c#本地MDB数据库连接
private void menuItem2_Click(object sender, System.EventArgs e)
{
try
{
//创建一个 OleDbConnection对象
string strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = ../../database/MDB数据库名称.mdb" ;
OleDbConnection myConn = new OleDbConnection ( strCon ) ;
string strCom = " SELECT * FROM 数据表名称" ;
//创建一个 DataSet对象
myDataSet = new DataSet ( ) ;
myConn.Open ( ) ;
OleDbDataAdapter myCommand = new OleDbDataAdapter ( strCom , myConn ) ;
myCommand.Fill ( myDataSet , "数据表名称" ) ;
myConn.Close ( ) ;
//关闭连接
statusBar1.Text="本地MDB数据库连接成功";
}
catch ( Exception ex )
{
statusBar1.Text="本地MDB数据库连接失败";
MessageBox.Show ( "连接本地MDB数据库发生错误:" + ex.ToString ( ) , "错误!" ) ;
}
}
c#远程MDB数据库连接
c#本地SQL数据库连接
private void menuItem3_Click(object sender, System.EventArgs e)
{
try
{
//创建一个 SqlConnection对象
string strCon = "Integrated Security=SSPI;Initial Catalog='数据库名称';Data Source='本地计算机名';User ID='登录用户名';Password='登录用户密码';Connect Timeout=30";
SqlConnection myConn = new SqlConnection ( strCon ) ;
string strCom = " SELECT * FROM 数据表名称" ;
//创建一个 DataSet对象
myDataSet = new DataSet ( ) ;
myConn.Open ( ) ;
SqlDataAdapter myCommand = new SqlDataAdapter ( strCom , myConn ) ;
myCommand.Fill ( myDataSet , "数据表名称" ) ;
myConn.Close ( ) ;
//关闭连接
statusBar1.Text="本地SQL数据库连接成功";
}
catch ( Exception ex1 )
{
statusBar1.Text="本地SQL数据库连接失败";
MessageBox.Show ( "连接本地SQL数据库发生错误:" + ex1.ToString ( ) , "错误!" ) ;
}
}
c#远程SQL数据库连接
private void menuItem10_Click(object sender, System.EventArgs e)
{
try
{
//创建一个SqlConnection对象
string strCon = "Initial Catalog='数据库名称';Server='远程IP地址,1433';User ID='登录用户名';Password='登录用户密码';Persist Security Info=True";
SqlConnection myConn = new SqlConnection ( strCon ) ;
string strCom = " SELECT * FROM 数据表名称" ;
//创建一个 DataSet对象
myDataSet = new DataSet ( ) ;
myConn.Open ( ) ;
SqlDataAdapter myCommand = new SqlDataAdapter ( strCom , myConn ) ;
myCommand.Fill ( myDataSet , "数据表名称" ) ;
myConn.Close ( ) ;
//关闭连接
statusBar1.Text="远程SQL数据库连接成功";
}
catch ( Exception ex2 )
{
statusBar1.Text="连接远程SQL数据库失败";
MessageBox.Show ( "连接远程SQL数据库发生错误:" + ex2.ToString ( ) , "错误!" ) ;
}
}