.NET数据库(MYSQL)操作
发布日期:2015-10-15 16:10:29
.NET数据库(MYSQL)操作 近期,客户来咨询使用mysql数据库的操作,现在这里把查询、增删改及连接数据库等操作的源代码整理统一说明,希望对您有所帮助。 1.查询数据库 源代码: public void BindGrid() { myConnection = new SqlConnection("server=localhost;" + "database=zhishi;uid=scm;pwd=scm"); SqlDataAdapter myCommand = new SqlDataAdapter("SELECT top 10 * FROM" + " wujml", myConnection); DataSet ds = new DataSet(); myCommand.Fill(ds); MyDataGrid.DataSource=ds; MyDataGrid.DataBind(); } 2.增删改数据库 源代码: public void AddAuthor_Click() { String insertCmd = "insert into wujml(wujid,wujbt,wujlj1) "+ "values ('99999','111','3131')"; SqlCommand myCommand = new SqlCommand(insertCmd, myConnection); myCommand.Connection.Open(); try { myCommand.ExecuteNonQuery(); //Message.InnerHtml = "Record Added " + insertCmd; } catch { //Console.WriteLine("{0} Second exception caught.", e); this.body.Text = "*************"; } myCommand.Connection.Close(); } 3.连接数据库 源代码: private void Page_Load(object sender, System.EventArgs e) { myConnection = new SqlConnection("server=localhost;" + "database=zhishi;uid=scm;pwd=scm"); //if (!IsPostBack) BindGrid(); } 4.连接ODBC数据库 源代码: // '参数:dsnName ODBC名,UserID 用户名,UserPwd 用户密码 public void ConnODBC(string dsnName ) { mCnnDB.Provider = "MSDASQL"; mCnnDB.ConnectionString = "Data Source='" + dsnName + "'"; mCnnDB.Open(mCnnDB.ConnectionString,"","",-1); } public void ConnODBC(string dsnName,string UserID, string UserPwd ) { mCnnDB.Provider = "MSDASQL"; mCnnDB.ConnectionString = "User ID='" +UserID + "';" + "Password='" + UserPwd + "';" + "Data Source='"+dsnName+ "'"; mCnnDB.Open(mCnnDB.ConnectionString,UserID,UserPwd,-1 ); } 5.连接SQL Server数据库 源代码: //参数:ServerName 服务器名,DBName 数据库名,UserID 用户名,UserPwd 用户密码 public void ConnSQLServer(string ServerName, string DBName) { mCnnDB.ConnectionString = "uid=;pwd= ;driver={SQL Server};" + "server=" +ServerName+ ";database=" + DBName; mCnnDB.Open(mCnnDB.ConnectionString,"sa","",-1); } public void ConnSQLServer(string ServerName, string DBName,string UserID,string UserPwd) { mCnnDB.ConnectionString = "uid='" + UserID + "';pwd='" + UserPwd + "' ;driver={SQL Server};" + "server=" + ServerName + ";database=" + DBName; mCnnDB.Open(mCnnDB.ConnectionString,UserID,UserPwd,-1);; } 上一条: url编码的转化问题 下一条: 总结C#中ref和out的区别
|