Java JDBC 在IDEA环境下连接MySQL

今天主要首次练习JDBC连接,作为新手,真的是花了不少时间,为了然后来着不花费太多时间,走弯路,

首先写上自己的代码,

 


 
  1. import java.sql.*;

  2. public class Main {

  3.  
  4. public static void main(String[] args) {

  5. // 1.注册驱动

  6. Connection conn = null;

  7. Statement statement = null;

  8. ResultSet res = null;

  9. try {

  10. Driver driver = new com.mysql.jdbc.Driver();

  11. DriverManager.registerDriver(driver);

  12. // 2.获取数据库连接

  13. String url = "jdbc:mysql://localhost:3306/bjnode?characterEncoding=utf8&useSSL=false";

  14. // String url = "url=jdbc:mysql://localhost:3306/bjnode/framework?characterEncoding=utf8&useSSL=false";

  15. String user = "root";

  16. String password = "zmd365236";

  17. conn = DriverManager.getConnection(url, user, password);

  18. // 3.获取数据操作的对象

  19. statement = conn.createStatement();

  20. // 4.执行SQL语句,DML语句

  21. String sql = "select e.ename as name,e.sal as sal ,s.grade " +

  22. "as grade from emp e join salgrade s on e.sal between " +

  23. "s.losal and s.hisal";

  24. res = statement.executeQuery(sql);

  25. // 5.处理查询结果集

  26. while (res.next()) {

  27. String enmae = res.getString("name");

  28. double sal = res.getDouble("sal");

  29. int grade = res.getInt("grade");

  30. System.out.println(enmae+" "+sal+" "+grade);

  31. }

  32. } catch (SQLException e) {

  33. e.printStackTrace();

  34. } finally {

  35. if (res != null) {

  36. try {

  37. res.close();

  38. } catch (SQLException e) {

  39. e.printStackTrace();

  40. }

  41. }

  42. }

  43.  
  44. }

  45. }


 

问题主要有两个,一个是JDBC不被识别,首先要在工程中加载MySQL的jar文件,具体解决方式可以参看http://blog.csdn.net/a153375250/article/details/50851049,基本上市这样的,也可以从Globallib里面添加jar文件,其次就是下面的代码,最后的useSSL=false一定要有,问号前面的内容就是你要访问的数据库的名字,这里特别说明,看很多都知道但是没有说明,容易误解。否侧就有警告,虽然可以出结果,

bjnode?characterEncoding=utf8&useSSL=false
 

posted @ 2018-07-28 16:36  IT晓白  阅读(131)  评论(0编辑  收藏  举报