1、如下是“Java连接MySQL数据库并进行简单查询”的源码:
源码一mysqlConnecter.java:
package mysql;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class mysqlConnecter {
//加载驱动所需
private static final String driver = "com.mysql.cj.jdbc.Driver";
//建立连接所需
private static final String con_url = "jdbc:mysql://localhost:3306/kkk?useSSL=false&serverTimezone=UTC";
private static final String user_name = "root";
private static final String user_passward = "123456";
/**
* 1、静态代码块加载驱动,因为
* 只需要运行一次
*/
static {
try {
Class.forName(driver);
System.out.println("加载驱动成功!");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 2、建立连接
* @return
* @throws SQLException
*/
protected static Connection getConnecter() throws SQLException {
Connection con = null;
con = DriverManager.getConnection(con_url, user_name, user_passward);
System.out.println("获取连接成功!");
return con;
}
/**
* 3、关闭连接
* @throws SQLException
*/
protected static String closeConnection(Connection con) throws SQLException {
String mg = "exit con!";
if(con != null) {
con.close();
mg = "succeed!";
System.out.println("关闭连接成功!");
}
return mg;
}
private static void main(String[] args) throws SQLException {
System.out.println(closeConnection(getConnecter()));
}
}
源码二msqlDataOperation.java:
package mysql;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class msqlDataOperation {
/**
* 对整张表进行查询
* @return
* @throws SQLException
*/
public static List<String> dataQuery() throws SQLException {
List<String> res = new ArrayList<String>();
//连接数据库
Connection con = null;
con = mysqlConnecter.getConnecter();
// //查询语句
// String sql = "select * from ?;";
//
// //获取语句预编译对象
// PreparedStatement ps = null;
// ps = con.prepareStatement(sql);
//
// //完善命令
// ps.setString(1, "one");
//
// //建立结果集并执行语句
// ResultSet rs = ps.executeQuery();
Statement stmt = con.createStatement();
String sql = "select * from one";
ResultSet rs = stmt.executeQuery(sql);
//处理结果集
while(rs.next()) {
String str = new String();
str = rs.getString("name");
res.add(str);
}
rs.close();
System.out.println("结果集关闭成功!");
stmt.close();
System.out.println("语句通道关闭成功!");
mysqlConnecter.closeConnection(con);
return res;
}
public static void main(String[] args) {
List<String> str = null;
try {
str = dataQuery();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//遍历输出
if(str!=null){
for(String out:str) {
System.out.println(out);
}
}
}
}
2、注
如下是”Java连接MySQL数据库并进行简单查询“的连接: