Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/****?serverTimezone=UTC"; //****是你要访问的数据库是哪个,mysql版本5.0以上需要在后面加上serverTimezone=UTC //String url = "jdbc:mysql://localhost:3306/****?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC"; String username = "****"; //数据库的用户名 String password = "****";//数据库的密码 Connection con = DriverManager.getConnection(url, username, password);
Statement statement = connection.createStatement(); String sql = "insert into user values(1,'Jackage','857857')";//插入一条数据 int executeUpdate = statement.executeUpdate(sql);//返回值表示改动了几条数据
String sql = "select name,password from user"; _//查询数据_ ResultSet rs = statement.executeQuery(sql);
if (executeUpdate > 0) { System.out.println("操作成功!!!"); } else { System.out.println("未发生改动!!!!"); }
while (rs.next()) { String uname = rs.getString("name"); String upwd = rs.getString("password"); System.out.println(uname+ " " + upwd); }
以上是JDBC访问数据库的简单步骤,中间我们还需要抛异常
除了Class.forName() 抛出ClassNotFoundException,其余方法全部抛SQLException
最后还需要关闭connection、statement、rs
关闭顺序与打开时的顺序相反,同时也要抛出异常
try { if(rs!=null)rs.close() if(stmt!=null) stmt.close(); if(connection!=null)connection.close(); } catch (SQLException e) { e.printStackTrace(); }
原文链接:https://www.cnblogs.com/change23/p/13512004.html