1.我们连接在使用Java连接数据库的时候,不管是Oracle数据库还是Mysql数据库,都需要一个对应的jar包,Oracle数据库需要的是ojdbc15.jar包,而Mysql数据库需要的是mysql-connector-java-5.1.7-bin.jar包,这两种在网上都可以很方便的找到。
2、Java连接Mysql的代码如下:
private static String url = "jdbc:mysql://localhost:3306/test"; private static String userName = "root"; private static String password = "root"; public static void main(String[] args) { MysqlConnectTest mysql= new MysqlConnectTest(); Connection con = mysql.getConnection(); if(con==null){ System.out.println("与mysql数据库连接失败!"); }else{ System.out.println("与mysql数据库连接成功!"); } }
3、MysqlConnectTest 类中getConnection()方法如下:
public Connection getConnection(){ Connection con = null; try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection(url, userName, password); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } return con; }
4、Mysql执行查看语句:
Statement sts = null; String sql = "select * from user_table "; ResultSet resul = null; try { sts = (Statement) con.createStatement(); resul = sts.executeQuery(sql); } catch (SQLException e) { e.printStackTrace(); } System.out.println("查询的结果如下:"); while(resul.next()){ System.out.println("user_id: "+resul.getString("user_id")+",user_name: "+resul.getString("user_name")+",user_sex: "+resul.getString("user_sex")); }
5、现在执行插入语句,代码如下:
String sql = "insert into user_table values ('3','thiscode','1','28','13351210773')"; int i = 0; try { sts = (Statement) con.createStatement(); i = sts.executeUpdate(sql); if(i == -1){ System.out.println("插入失敗"); }else{ System.out.println("插入成功"); } } catch (SQLException e) { e.printStackTrace(); }
说明
Statement和PreparedStatement
以上就是Java如何连接Mysql数据库的详细内容,更多请关注php中文网其它相关文章!
……