JDBC is rarely used in current development. The Mybatis and Hibernate frameworks have perfectly encapsulated JDBC and mapped it to entity classes. We only need a simple call to complete a lot of work, especially Mybatis, which is more flexible. Change. However, as a professional developer, we must have a deep understanding of JDBC so that we can better use the ORM framework.
1. When we use Java to connect to the database, whether it is an Oracle database or a Mysql database, we need a corresponding jar package, which is required by the Oracle database. It is the ojdbc15.jar package, and the Mysql database requires the mysql-connector-java-5.1.7-bin.jar package. Both of these can be easily found online.
2. The code for Java connection to Mysql is as follows:
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. The getConnection() method in the MysqlConnectTest class is as follows :
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 execution view statement:
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. Now execute the insert statement, the code is as follows:
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(); }
Description
Statement and PreparedStatement
The above is the detailed content of How to connect to Mysql database in Java?. For more information, please follow other related articles on the PHP Chinese website!