今天主要首次练习JDBC连接,作为新手,真的是花了不少时间,为了然后来着不花费太多时间,走弯路,
首先写上自己的代码,
-
import java.sql.*;
-
public class Main {
-
public static void main(String[] args) {
-
// 1.注册驱动
-
Connection conn = null;
-
Statement statement = null;
-
ResultSet res = null;
-
try {
-
Driver driver = new com.mysql.jdbc.Driver();
-
DriverManager.registerDriver(driver);
-
// 2.获取数据库连接
-
String url = "jdbc:mysql://localhost:3306/bjnode?characterEncoding=utf8&useSSL=false";
-
// String url = "url=jdbc:mysql://localhost:3306/bjnode/framework?characterEncoding=utf8&useSSL=false";
-
String user = "root";
-
String password = "zmd365236";
-
conn = DriverManager.getConnection(url, user, password);
-
// 3.获取数据操作的对象
-
statement = conn.createStatement();
-
// 4.执行SQL语句,DML语句
-
String sql = "select e.ename as name,e.sal as sal ,s.grade " +
-
"as grade from emp e join salgrade s on e.sal between " +
-
"s.losal and s.hisal";
-
res = statement.executeQuery(sql);
-
// 5.处理查询结果集
-
while (res.next()) {
-
String enmae = res.getString("name");
-
double sal = res.getDouble("sal");
-
int grade = res.getInt("grade");
-
System.out.println(enmae+" "+sal+" "+grade);
-
}
-
} catch (SQLException e) {
-
e.printStackTrace();
-
} finally {
-
if (res != null) {
-
try {
-
res.close();
-
} catch (SQLException e) {
-
e.printStackTrace();
-
}
-
}
-
}
-
}
-
}
问题主要有两个,一个是JDBC不被识别,首先要在工程中加载MySQL的jar文件,具体解决方式可以参看http://blog.csdn.net/a153375250/article/details/50851049,基本上市这样的,也可以从Globallib里面添加jar文件,其次就是下面的代码,最后的useSSL=false一定要有,问号前面的内容就是你要访问的数据库的名字,这里特别说明,看很多都知道但是没有说明,容易误解。否侧就有警告,虽然可以出结果,
bjnode?characterEncoding=utf8&useSSL=false