MySQLDBHelper

package DBUnitily;

import java.io.*;
import java.sql.*;
import java.util.*;

public class MySQLDBHelper {
private String connString="db";

public MySQLDBHelper(){


}


public MySQLDBHelper(String coString){

connString=coString;
}

// 获取连接
private Connection getConnection() {
Connection con = null;
String driver_class = null;
String driver_url = null;
String database_user = null;
String database_password = null;
try {
InputStream fis = this.getClass().getResourceAsStream("/"+connString+".properties");
Properties p = new Properties();
p.load(fis);
driver_class = p.getProperty("driver").trim();
driver_url = p.getProperty("url").trim();
database_user = p.getProperty("user").trim();
database_password = p.getProperty("password").trim();
Class.forName(driver_class);
con = DriverManager.getConnection(driver_url, database_user, database_password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}


// 关闭连接
private void closeAll(Connection con, PreparedStatement pst, ResultSet rst) {
if (rst != null) {
try {
rst.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


if (pst != null) {
try {
pst.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


if (con != null) {
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


}


private List<Map<String, Object>> getResultMap(ResultSet rs) throws SQLException {
Map<String, Object> hm = null;
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
ResultSetMetaData rsmd = rs.getMetaData();
int count = rsmd.getColumnCount();
while (rs.next()) {
hm = new HashMap<String, Object>();
for (int i = 1; i <= count; i++) {
String key = rsmd.getColumnLabel(i);
Object value = rs.getString(i);
hm.put(key, value);
}
list.add(hm);
}
return list;
}


// 获取数据的总条数
private int dataCount(String sql) {
sql = "SELECT count(*) as num FROM (" + sql + ") tcount";
int count = 0;
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
conn = getConnection();// 获取连接对象
try {
pstmt = conn.prepareStatement(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // 预处理sql
try {
rs = pstmt.executeQuery();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
while (rs.next()) {
count = Integer.parseInt(rs.getString("num"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
closeAll(conn, pstmt, rs);// 关闭连接
return count;


}


// 查询数据
public List<Map<String, Object>> query(String sql, Object[] agrs) {
ResultSet rs = null;
List<Map<String, Object>> mapList = null;
try {
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = getConnection();// 获取连接对象
pstmt = conn.prepareStatement(sql);// 预处理sql
if (agrs != null && agrs.length > 0) {


for (int i = 0; i < agrs.length; i++) {
pstmt.setObject(i + 1, agrs[i]);
}
}
rs = pstmt.executeQuery();// 由于不需要返回结果集,所以直接使用executeUpdate
if (rs != null) {
mapList = getResultMap(rs);
}


} finally {
closeAll(conn, pstmt, rs);// 关闭连接
}
} catch (Exception e) {


}
return mapList;
}


// 增删改
public int update(String sql, Object[] agrs) {
int result = -1;
try {
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = getConnection();// 获取连接对象
pstmt = conn.prepareStatement(sql);// 预处理sql
if (agrs != null && agrs.length > 0) {


for (int i = 0; i < agrs.length; i++) {
pstmt.setObject(i + 1, agrs[i]);
}
}
result = pstmt.executeUpdate();// 由于不需要返回结果集,所以直接使用executeUpdate
} finally {
closeAll(conn, pstmt, null);// 关闭连接
}
} catch (Exception e) {


}
return result;
}


// 分页数据的 Object[] 数组第一个值是 数据集 第二个值是 数据总数
public Object[] queryPage(String sql, String orderBy, int pageIndex, int pageSize) {
Object[] objArry = new Object[2];
String strSQL = "SELECT (@i:=@i+1) AS row_id,tab.* FROM (" + sql + ")  AS TAB,(SELECT @i:=0) AS it ORDER BY "
+ orderBy + " LIMIT " + (pageIndex - 1) + "," + pageSize;
List<Map<String, Object>> mapList = query(strSQL, null);
int count = dataCount(sql);
objArry[0] = mapList;
objArry[1] = count;
return objArry;
}
}
可以使用以下代码实现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("添加失败!"); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值