IntelliJ IDEA中JAVA连接MYSQL

时间:2021-01-30 05:59:46

1.下载mysql包

IntelliJ IDEA中JAVA连接MYSQL

IntelliJ IDEA中JAVA连接MYSQL

2.项目中引入mysql包

IntelliJ IDEA中JAVA连接MYSQL

IntelliJ IDEA中JAVA连接MYSQL

IntelliJ IDEA中JAVA连接MYSQL

3.连接数据库,查询结果

IntelliJ IDEA中JAVA连接MYSQL

IntelliJ IDEA中JAVA连接MYSQL

看jdbc数据库连接类

package Facade;
import java.sql.*;
/**
* Created by Jiqing on 2016/10/18.
*/
public class JDBCFacade { private Connection conn=null;
private Statement statement=null; public void open(String driver,String jdbcUrl,String userName,String userPwd) {
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(jdbcUrl,userName,userPwd);
statement = conn.createStatement();
}
catch (Exception e) {
e.printStackTrace();
}
} public int executeUpdate(String sql) {
try {
return statement.executeUpdate(sql);
}
catch (SQLException e) {
e.printStackTrace();
return -1;
}
} public ResultSet executeQuery(String sql) {
try {
return statement.executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace();
return null;
}
} public void close() {
try {
conn.close();
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

客户端执行

package Facade;
import java.sql.ResultSet; /**
* Created by Jiqing on 2016/10/18.
*/
public class Client {
public static void main(String args[])
{
try {
JDBCFacade jdbc= new JDBCFacade();
jdbc.open("com.mysql.jdbc.Driver","jdbc:mysql://localhost:3306/tpshop","root","123456");
ResultSet rs = jdbc.executeQuery("select * from tp_admin"); while(rs.next()){
String email = rs.getString("email") ;
System.out.println(email); }
}
catch (Exception e)
{
e.printStackTrace();
} }
}