JDBC连接Mysql常见问题汇总

                                                           JDBC连接Mysql常见问题汇总

JDBC连接全过程请参考《Java MySQL 连接》

http://www.runoob.com/java/java-mysql-connect.html

错误1:

JDBC链接警告WARN: Establishing SSL connection without server's identity verification is not recommended.

参考:http://blog.csdn.net/qq_15581405/article/details/52403576?locationNum=13

错误2:

java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/

参考:

http://blog.csdn.net/xiaofanku/article/details/51542495

http://www.blogjava.net/w2gavin/articles/217864.html

http://blog.csdn.net/SpeedGodDeer/article/details/40150027

错误3:

MySQL java连接被拒绝:java.sql.SQLException: Access denied for user 'root'@'****' (using password: YES)

参考:http://www.cnblogs.com/nextsummer/p/6736998.html


grant all privileges on *.* to root@'%' identified by '******' //***表示数据库连接密码,%也要对应修改用户名

连接数据库

MySQLDemo.java 文件代码

package com.runoob.test;


import java.sql.*;


public class MySQLDemo {

//JDBC驱动名及数据库URL
static final String JDBC_DRIVER="com.mysql.jdbc.Driver";
static final String DB_URL="jdbc:mysql://localhost:3306/RUNOOB?useUnicode=true&characterEncoding=utf-8&useSSL=false";

//数据库的用户名与密码,需要根据自己设置
static final String USER="root";
static final String PASS="123456";

public static void main(String[] args){
Connection conn=null;
Statement stmt=null;
try{
//注册JDBC驱动‘
Class.forName("com.mysql.jdbc.Driver");

//打开链接
System.out.println("连接数据库...");
conn=DriverManager.getConnection(DB_URL,USER,PASS);

//执行查询
System.out.println("实例化Statement对...");
stmt=conn.createStatement();
String sql;
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.print("ID:"+id);
System.out.print(",站点名称:"+name);
System.out.print(",站点URL:"+url);
System.out.print("\n");
}
//完成后关闭
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//处理JDBC错误
se.printStackTrace();
}catch(Exception e){
//处理Class.forName错误
e.printStackTrace();
}finally{
//关闭资源
try{
if(stmt!=null) stmt.close();
}catch(SQLException se2){
}//什么都不做
try{
if(conn!=null)conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
System.out.println("Goodbys!");
}

}

JDBC连接Mysql常见问题汇总_第1张图片

你可能感兴趣的:(JDBC连接Mysql常见问题汇总)