jdbc连接mysql数据库注意事项
程序员文章站
2022-05-27 23:12:14
...
1.导入mysql驱动 http://blog.csdn.net/a153375250/article/details/50851049
2.开放机器访问权限
mysql>GRANT ALL PRIVILEGES ON *.* TO 'root'@'%'IDENTIFIED BY '123456' WITH GRANT OPTION;
mysql>FLUSH PRIVILEGES
3.关闭防火墙
[[email protected] ~]# systemctl stop firewalld
代码
import java.sql.*;
public class TestDemo {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://172.16.2.116:3306/RUNOOB";
static final String USER = "root";
static final String PASS = "520224";
public static void main(String[] args) throws Exception{
try{
//加载mysql驱动
Class.forName("JDBC_DRIVER");
//建立连接
Connection conn = DriverManager.getConnection(DB_URL,USER,PASS);
//创建语句实例
Statement stmt = conn.createStatement();
String sql= "SELECT id, name, url FROM websites";
//执行查询
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String url = rs.getString("url");
System.out.println(id+","+name+","+ url);
}
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
// 处理 JDBC 错误
se.printStackTrace();
}catch(Exception e){
// 处理 Class.forName 错误
e.printStackTrace();
}
}
}