asp.net连接MySQL数据库的代码实现
时间: 2023-11-03 13:02:04 浏览: 105
可以使用以下代码实现asp.net连接MySQL数据库:
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using MySql.Data.MySqlClient;
public class MySQLDBHelper
{
private static string connectionString = "server=localhost;user id=root;password=123456;database=test;Charset=utf8;";
public static DataTable ExecuteDataTable(string commandText, CommandType commandType, params MySqlParameter[] parameters)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
using (MySqlCommand command = new MySqlCommand(commandText, connection))
{
command.CommandType = commandType;
if (parameters != null)
{
command.Parameters.AddRange(parameters);
}
MySqlDataAdapter adapter = new MySqlDataAdapter(command);
DataTable dataTable = new DataTable();
adapter.Fill(dataTable);
return dataTable;
}
}
}
public static int ExecuteNonQuery(string commandText, CommandType commandType, params MySqlParameter[] parameters)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
using (MySqlCommand command = new MySqlCommand(commandText, connection))
{
command.CommandType = commandType;
if (parameters != null)
{
command.Parameters.AddRange(parameters);
}
connection.Open();
int result = command.ExecuteNonQuery();
return result;
}
}
}
}
```
其中,MySQLDBHelper是一个帮助类,提供了两个静态方法,一个用于执行SELECT语句并返回DataTable,另一个用于执行INSERT/UPDATE/DELETE等操作并返回受影响的行数。需要将connectionString变量替换为自己的MySQL连接字符串。使用示例:
```
MySqlParameter[] parameters = new MySqlParameter[] { new MySqlParameter("@name", "张三"), new MySqlParameter("@age", 20) };
string sql = "INSERT INTO student (name, age) VALUES (@name, @age)";
int result = MySQLDBHelper.ExecuteNonQuery(sql, CommandType.Text, parameters);
if (result > 0)
{
Response.Write("添加成功!");
}
else
{
Response.Write("添加失败!");
}
```
阅读全文