OleDbConnection与SqlConnection的区别与使用方法

区别介绍:

    OleDbConnection适合于连接任何类型的数据库(如Oracle,SQL   Server,ACCESS等),其命名空间为:using System.Data.OleDb;。而SqlConnection是专门用来连接SQL   Server(MS   SQL)数据库的,其命名空间为:using System.Data.SqlClient。在对数据库的操作中,如果用到了OleDbConnection,那么对数据库的操作,比如连接池就要用到 OleDbDataAdapter 和 操作命令 用 OleDbCommand ,同样的在用到了SqlConnection时, 就要用到SqlDataAdaper  和 SqlcCommand。在一定情况下,如果需要对数据表中具体到某一字段的数据进行操作时(比如想要得到某一行某一列的具体的数据),OleDbConnection 可以用OleDbDataReader,SqlConnection可以用 SqlDataReader读取器进行数据读取。其次针对以上两种情况,也均可以采用连接池,dataset    ,datetable的联合使用获取,自己想要的某一行某一列的具体的数据.  针对以上具体方法和属性的使用可参考MSDN的讲解

 

使用方法:

OleDB:

            OleDbConnection conn = new OleDbConnection();
        conn.ConnectionString = "Provider=SQLOLEDB;DataSource=PCBDEVELOP01\\SQL2008';InitialCatalog=MyDB_YK;uid=reportAdmin;pwd=reportAdmin#";
            try
            {
                conn.Open();
                MessageBox.Show("OK");
                conn.Close();
            }
            catch
            {
                MessageBox.Show("error");
            }

注:

连接字串还可以使用Trusted_Connection=Yes来声明这是一个值得信任的连接字串,而不需要输入用户名和密码,示例代码如下所示。

            string str2 =

            "Provider=SQLOLEDB;Data Source=(local);Initial Catalog=mytable;Trusted_Connection=Yes";

            OleDbConnection con = new OleDbConnection(str2);

 

SqlConnect:

            string strCon = @"server='PCBDEVELOP01\SQL2008';database='MyDB_YK';uid='reportAdmin';pwd='reportAdmin#'";
            SqlConnection conn=new SqlConnection(strCon);
            try
            {
                conn.Open();
                MessageBox.Show("数据库联接成功");
                conn.Close();
            }
            catch
            {
                MessageBox.Show("数据库联接失败");
            }

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Data.OleDb; namespace DormMIS { /// <summary> /// Form1 的摘要说明。 /// </summary> public class Login : System.Windows.Forms.Form { private System.Windows.Forms.Button btClose;//取消按钮 private System.Windows.Forms.Button btAdd; private System.Windows.Forms.TextBox password; private System.Windows.Forms.TextBox name; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label1; /// <summary> /// 必需的设计器变量。 /// </summary> private System.ComponentModel.Container components = null; private OleDbConnection oleConnection1 = null; public Login() { // // Windows 窗体设计器支持所必需的 // InitializeComponent(); this.oleConnection1=new OleDbConnection(DormMIS.database.dbConnection.connection); // // TODO: 在 InitializeComponent 调用后添加任何构造函数代码 // } /// <summary> /// 清理所有正在使用的资源。 /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows 窗体设计器生成的代码 /// <summary> /// 设计器支持所需的方法 - 不要使用代码编辑器修改 /// 此方法的内容。 /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Login)); this.btClose = new System.Windows.Forms.Button(); this.btAdd = new System.Windows.Forms.Button(); this.password = new System.Windows.Forms.TextBox(); this.name = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.SuspendLayout(); // // btClose // this.btClose.FlatStyle = System.Windows.Forms.FlatStyle.Popup; this.btClose.ForeColor = System.Drawing.Color.Black; this.btClose.Location = new System.Drawing.Point(168, 156); this.btClose.Name = "btClose"; this.btClose.Size = new System.Drawing.Size(75, 23); this.btClose.TabIndex = 20; this.btClose.Text = "取消"; this.btClose.Click += new System.EventHandler(this.btClose_Click); // // btAdd // this.btAdd.FlatStyle = System.Windows.Forms.FlatStyle.Popup; this.btAdd.ForeColor = System.Drawing.Color.Black; this.btAdd.Location = new System.Drawing.Point(48, 156); this.btAdd.Name = "btAdd"; this.btAdd.Size = new System.Drawing.Size(75, 23); this.btAdd.TabIndex = 19; this.btAdd.Text = "确定"; this.btAdd.Click += new System.EventHandler(this.btAdd_Click); // // password // this.password.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.password.Location = new System.Drawing.Point(128, 116); this.password.Name = "password"; this.password.PasswordChar = '*'; this.password.Size = new System.Drawing.Size(100, 21); this.password.TabIndex = 18; this.password.Text = "admin"; // // name // this.name.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.name.Location = new System.Drawing.Point(128, 76); this.name.Name = "name"; this.name.Size = new System.Drawing.Size(100, 21); this.name.TabIndex = 17; this.name.Text = "admin"; this.name.TextChanged += new System.EventHandler(this.name_TextChanged); // // label3 // this.label3.Font = new System.Drawing.Font("宋体", 10.5F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.label3.ForeColor = System.Drawing.Color.Black; this.label3.Location = new System.Drawing.Point(64, 116); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(56, 23); this.label3.TabIndex = 16; this.label3.Text = "密 码"; // // label2 // this.label2.Font = new System.Drawing.Font("宋体", 10.5F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.label2.ForeColor = System.Drawing.Color.Black; this.label2.Location = new System.Drawing.Point(64, 76); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(56, 23); this.label2.TabIndex = 15; this.label2.Text = "用户名"; // // label1 // this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 18F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.label1.ForeColor = System.Drawing.Color.Black; this.label1.Location = new System.Drawing.Point(40, 24); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(228, 28); this.label1.TabIndex = 14; this.label1.Text = "宿舍管理信息系统"; // // Login // this.AutoScaleBaseSize = new System.Drawing.Size(6, 14); this.BackColor = System.Drawing.Color.Ivory; this.ClientSize = new System.Drawing.Size(304, 210); this.Controls.Add(this.btClose); this.Controls.Add(this.btAdd); this.Controls.Add(this.password); this.Controls.Add(this.name); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "Login"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "登录"; this.Load += new System.EventHandler(this.Login_Load); this.ResumeLayout(false); this.PerformLayout(); } #endregion /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { Application.Run(new Login()); } private void btAdd_Click(object sender, System.EventArgs e) { if(name.Text.Trim()==""||password.Text.Trim()=="") MessageBox.Show("请输入用户名和密码","提示"); else { oleConnection1.Open(); OleDbCommand cmd=new OleDbCommand("",oleConnection1); string sql="select * from userinfo where UName='"+name.Text.Trim()+"' and PWD='"+password.Text.Trim()+"'"; cmd.CommandText=sql; if (null!=cmd.ExecuteScalar()) { //隐藏登录窗口 this.Visible=false; //创建并打开主界面 Main main=new Main(); main.Tag=this.FindForm(); OleDbDataReader dr; cmd.CommandText=sql; dr=cmd.ExecuteReader(); dr.Read(); main.statusBarPanel2.Text=name.Text.Trim(); main.ShowDialog(); } else MessageBox.Show("用户名或密码错误","警告"); } oleConnection1.Close(); } private void btClose_Click(object sender, System.EventArgs e) { this.Close(); } private void name_TextChanged(object sender, EventArgs e) { } } }
要将Excel数据插入SqlServer中并避免重复数据,可以使用以下步骤: 1. 将Excel数据读取到DataTable中。 2. 在DataTable中检查是否存在重复数据,如果存在则删除重复数据。 3. 使用SqlBulkCopy将数据插入到SqlServer中。 以下是示例代码: ```csharp using System.Data; using System.Data.OleDb; using System.Data.SqlClient; //连接Excel文件 string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\\sample.xlsx;Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\""; OleDbConnection excelConn = new OleDbConnection(connString); excelConn.Open(); //读取Excel数据到DataTable中 string sql = "SELECT * FROM [Sheet1$]"; OleDbDataAdapter adapter = new OleDbDataAdapter(sql, excelConn); DataTable excelData = new DataTable(); adapter.Fill(excelData); excelConn.Close(); //检查是否存在重复数据 for (int i = excelData.Rows.Count - 1; i >= 0; i--) { DataRow row = excelData.Rows[i]; if (IsDuplicate(row)) { excelData.Rows.Remove(row); } } //将数据插入到SqlServer中 string sqlServerConnString = "Data Source=.;Initial Catalog=TestDB;Integrated Security=True;"; SqlConnection sqlServerConn = new SqlConnection(sqlServerConnString); sqlServerConn.Open(); SqlTransaction tran = sqlServerConn.BeginTransaction(); try { using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlServerConn, SqlBulkCopyOptions.Default, tran)) { bulkCopy.DestinationTableName = "Person"; bulkCopy.ColumnMappings.Add("Name", "Name"); bulkCopy.ColumnMappings.Add("Age", "Age"); bulkCopy.WriteToServer(excelData); } tran.Commit(); } catch (Exception ex) { tran.Rollback(); throw ex; } finally { sqlServerConn.Close(); } //检查是否存在重复数据的方法 private bool IsDuplicate(DataRow row) { string name = row["Name"].ToString(); int age = int.Parse(row["Age"].ToString()); string sql = "SELECT COUNT(*) FROM Person WHERE Name=@Name AND Age=@Age"; using (SqlConnection conn = new SqlConnection(sqlServerConnString)) { SqlCommand cmd = new SqlCommand(sql, conn); cmd.Parameters.AddWithValue("@Name", name); cmd.Parameters.AddWithValue("@Age", age); conn.Open(); int count = (int)cmd.ExecuteScalar(); if (count > 0) { return true; } else { return false; } } } ``` 以上代码中使用了IsDuplicate方法来检查是否存在重复数据,该方法查询了目标表中是否存在相同的Name和Age值。如果存在则返回true,否则返回false。在使用SqlBulkCopy插入数据时,应该先将Excel数据读取到DataTable中,然后在DataTable中检查是否存在重复数据,最后再将数据插入到SqlServer中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值