Csharp/C#教程:C#连接MySQL的两个简单代码示例分享

实现代码一、使用的是mysql自带的驱动安装一下即可

这是一个简单的例子。
在这里有个问题:dataset如果没设主键的话,可能会引起一些对数库操作的问题,比如会造成updata出现错误。

staticvoidMain(string[]args) { stringsqlstr="select*frommanavatar"; MySQLConnectionDBConn=newMySQLConnection(newMySQLConnectionString("192.168.0.13","flashdata","root","root",3306).AsString); DBConn.Open(); //MySQLDataAdaptermyadap=newMySQLDataAdapter(sqlstr,conn); MySQLCommandDBComm=newMySQLCommand(sqlstr,DBConn); MySQLDataReaderDBReader=DBComm.ExecuteReaderEx();//DBComm.ExecuteReaderEx(); MySQLDataAdapterDTAdapter=newMySQLDataAdapter(sqlstr,DBConn); DataSetmyDataSet=newDataSet(); DTAdapter.Fill(myDataSet,"manavatar"); try { while(DBReader.Read()) { //Console.WriteLine("11"); Console.WriteLine("DBReader:{0},tttddddd:{1},tt{2}",DBReader.GetString(0),DBReader.GetString(1),DBReader.GetString(3)); } Console.WriteLine("0000"); } catch(Exceptione) { Console.WriteLine("读入失败!"+e.ToString()); } finally { Console.WriteLine("DBReader关闭"); Console.WriteLine("DBConn关闭"); DBReader.Close(); //DBConn.Close(); } for(inti=0;i<myDataSet.Tables["manavatar"].Rows.Count;i++) { Console.WriteLine("{0}",myDataSet.Tables["manavatar"].Rows[2]["user"]); } }

方法二、

贴一份示例代码。非常适合于初学者使用。
C#访问mysql

usingSystem; usingSystem.Collections.Generic; usingSystem.Text; usingMySql.Data.MySqlClient; usingSystem.Data; usingSystem.Data.Common; namespaceSybaseUtilTest { classProgram { //https://bugs.mysql.com/47422,有兴趣的朋友,可以看看这个bug是怎么回事 staticvoidtestDataAdapter() { try { MySqlClientFactoryfactory=MySqlClientFactory.Instance; DbConnectionconn=factory.CreateConnection(); conn.ConnectionString=string.Format("server={0};userid={1};password={2};database={3};port={4};pooling=false", "localhost","root","passwd","test",3306); conn.Open(); DbDataAdapterda=factory.CreateDataAdapter(); da.SelectCommand=conn.CreateCommand(); da.SelectCommand.CommandText="select*fromt12345"; da.DeleteCommand=conn.CreateCommand(); da.DeleteCommand.CommandText="deletefromt12345whereid=@id"; DbParameterparam=factory.CreateParameter(); param.ParameterName="@id"; param.DbType=DbType.Int32; param.SourceColumn="id"; param.SourceVersion=DataRowVersion.Current; da.DeleteCommand.Parameters.Add(param); da.DeleteCommand.UpdatedRowSource=UpdateRowSource.None; DataTabledt=newDataTable("t12345"); da.Fill(dt); intindex=0; foreach(DataRowoindt.Rows) { if(o["id"].Equals(4)) { Console.WriteLine(String.Format("index={0},todeleteid=4,col2={1}",index,o["col2"])); break; } index++; } dt.Rows[index].Delete(); da.Update(dt); dt.AcceptChanges(); da.Dispose(); conn.Close(); } catch(Exceptionex) { Console.WriteLine(ex.Source+"" +ex.Message+"" +ex.StackTrace); } } staticvoidMain(string[]args) { testDataAdapter(); } } }

上述就是C#学习教程:C#连接MySQL的两个简单代码示例分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/907890.html

(0)
上一篇 2021年10月25日
下一篇 2021年10月25日

精彩推荐