java连接mySql我要详细步骤
发布网友
发布时间:2022-04-25 05:37
我来回答
共1个回答
热心网友
时间:2022-04-08 20:41
您好,希望我的答案对您有所帮助:此类为一个数据库连接类,用它可以实现java和MySql的链接。 package com.handson.model.connection;import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;public class ConnectionFactory { private static final String driverClassName = "com.mysql.jdbc.Driver";
private static final String url = "jdbc:mysql://localhost:3306/message";
private static final String user = "root";
private static final String password = "root";
/**
* 返回连接
*
* @return Connection
*/
public static Connection getConnction() {
Connection conn = null;
try {
Class.forName(driverClassName);
conn = DriverManager.getConnection(url,
user, password);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
} /**
* 关闭连接
*
* @param dbConnection
* Connection
*/
public static void closeConnection(Connection conn) {
try {
if (conn != null && (!conn.isClosed())) {
conn.close();
}
} catch (SQLException sqlEx) {
sqlEx.printStackTrace();
}
} /**
* 关闭结果集
*
* @param res
* ResultSet
*/
public static void closeResultSet(ResultSet res) {
try {
if (res != null) {
res.close();
res = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
} /**
* 关闭语句
*
* @param pStatement
* PreparedStatement
*/ public static void closeStatement(PreparedStatement pStatement) {
try {
if (pStatement != null) {
pStatement.close();
pStatement = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}