.net链接mysql简单而高效

时间:2025-01-18 08:40:21

using System;

using System.Collections.Generic;

using System.Data.SqlClient;

using System.Data;

using System.Linq;

using System.Web;

using MySql.Data;

using MySql.Data.MySqlClient;

using System.Configuration;

namespace WebApplication2.Model

{

public class MysqlHELPER

{

//public static string Conntr ="Server=118.195.237.101;port=3306;database=esab;user=root;password=flx123456;charset=utf8;";

private static string Conntr=ConfigurationManager.ConnectionStrings["mysql"].ConnectionString;

public static DataTable RunSQLReturnDT(string SQLString)

{

object lockThis = new object();

lock (lockThis)

{

using (MySqlConnection connection = new MySqlConnection(Conntr))

{

DataSet ds = new DataSet();

connection.Open(); MySqlDataAdapter command = new MySqlDataAdapter(SQLString, connection); command.Fill(ds, "ds"); connection.Close(); return ds.Tables[0]; } } } /// <summary> /// 执行SQL,返回是否执行成功 /// </summary> /// <param name="sql">sql语句,如:delete,update,insert等</param> /// <returns>True:成功,False失败</returns> public static bool RunSQL(string SQLString) { object lockThis = new object(); lock (lockThis) { using (MySqlConnection connection = new MySqlConnection(Conntr)) { using (MySqlCommand cmd = new MySqlCommand(SQLString, connection)) { try { connection.Open(); int rows = cmd.ExecuteNonQuery(); connection.Close(); if (rows > 0) return true; else return false; } catch (System.Data.SqlClient.SqlException e) { connection.Close(); throw e; } } } } } }

}

应用:

public DataTable PgfData(string partname,string serialnumber )

{

string sql = “”;

DataTable dt= MysqlHELPER.RunSQLReturnDT(sql);

return dt;

}