C#连接MySQL的两个简单代码示例
程序员文章站
2023-12-12 08:52:52
实现代码一、使用的是mysql自带的驱动安装一下即可
这是一个简单的例子。
在这里有个问题:dataset如果没设主键的话,可能会引起一些对数库操作的问题,比如会造成u...
实现代码一、使用的是mysql自带的驱动安装一下即可
这是一个简单的例子。
在这里有个问题:dataset如果没设主键的话,可能会引起一些对数库操作的问题,比如会造成updata出现错误。
static void main(string[] args) { string sqlstr = "select * from manavatar"; mysqlconnection dbconn = new mysqlconnection(new mysqlconnectionstring("192.168.0.13", "flashdata", "root", "root", 3306).asstring); dbconn.open(); //mysqldataadapter myadap = new mysqldataadapter(sqlstr, conn); mysqlcommand dbcomm = new mysqlcommand(sqlstr,dbconn); mysqldatareader dbreader = dbcomm.executereaderex(); //dbcomm.executereaderex(); mysqldataadapter dtadapter = new mysqldataadapter(sqlstr,dbconn); dataset mydataset = new dataset(); dtadapter.fill(mydataset,"manavatar"); try { while (dbreader.read()) { //console.writeline("11"); console.writeline("dbreader:{0},\t\t\tddddd:{1},\t\t {2}",dbreader.getstring(0), dbreader.getstring(1),dbreader.getstring(3)); } console.writeline("0000"); } catch (exception e) { console.writeline("读入失败!"+e.tostring()); } finally { console.writeline("dbreader关闭"); console.writeline("dbconn关闭"); dbreader.close(); //dbconn.close(); } for (int i = 0; i < mydataset.tables["manavatar"].rows.count; i++) { console.writeline("{0}",mydataset.tables["manavatar"].rows[2]["user"]); } }
方法二、
贴一份示例代码。非常适合于初学者使用。
c#访问mysql
using system; using system.collections.generic; using system.text; using mysql.data.mysqlclient; using system.data; using system.data.common; namespace sybaseutiltest { class program { // http://bugs.mysql.com/47422, 有兴趣的朋友,可以看看这个bug是怎么回事 static void testdataadapter() { try { mysqlclientfactory factory = mysqlclientfactory.instance; dbconnection conn = factory.createconnection(); conn.connectionstring = string.format("server={0};user id={1}; password={2}; database={3}; port={4}; pooling=false", "localhost", "root", "passwd", "test", 3306); conn.open(); dbdataadapter da = factory.createdataadapter(); da.selectcommand = conn.createcommand(); da.selectcommand.commandtext = "select * from t12345"; da.deletecommand = conn.createcommand(); da.deletecommand.commandtext = "delete from t12345 where id = @id"; dbparameter param = 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; datatable dt = new datatable("t12345"); da.fill(dt); int index = 0; foreach ( datarow o in dt.rows ) { if (o["id"].equals(4)) { console.writeline(string.format("index={0}, to delete id = 4, col2 = {1}" , index, o["col2"])); break; } index++; } dt.rows[index].delete(); da.update(dt); dt.acceptchanges(); da.dispose(); conn.close(); } catch (exception ex) { console.writeline(ex.source + " " + ex.message + " " + ex.stacktrace); } } static void main(string[] args) { testdataadapter(); } } }
以上就是小编为大家整理的c#连接mysql数据库的方法,需要的朋友可以参考一下。