Java Database notes (1): jdbc connects to the mysql database, jdbcmysql
Recently I learned java and wrote a simple student information management system, which is interactive but not connected to a database. Therefore, it can only be used as a demonstration and cannot store data. Therefore, I started the database. I learned the basic knowledge of relational databases and the syntax of the SQL language in two hours, and then started to get started. The following are study notes:
1. Download mysql-connector-java-5.1.7-bin.jar
JDBC is composed of java classes in many java. SQL packages and supports accessing relational data in databases and other forms. First need to download the jdbc driver from the official website, http://dev.mysql.com/downloads/connector/j/
2. Add to the accessible java path
The practice I found online is to set the absolute path of the mysql-connector-java-5.1.7-bin.jar in classpath, for my convenience, put it here in % JAVA_HOME %/lib/mysql-connector-java-5.1.7-bin.jar, and then add it to the environment variable.
The problem is that after I set it, I wrote a simple program to test whether the driver can be found, but failed:
package com.xtest;import java.sql.*;public class main { public static void main(String[] args) { try{ Class.forName("com.mysql.jdbc.Driver"); }catch(ClassNotFoundException e){ System.out.println("con't find the driver"); e.printStackTrace(); } }}
Sorry, you can only find a solution. You can right-click the java project you want to run and choose build path> add external archives ......, Then add the mysql-connector-java-5.1.7-bin.jar to it, so it appears under the Referenced Library, run through! But I think this is a little troublesome, because every project needs to be added once separately, so there is a better solution or a deeper understanding. Please @ me, thank you!
3. Write Test Cases
I created a student class in the person library in mysql. I was lazy and only wrote the id and name items, and then inserted two records. The following code is used:
package com.jdbc;import java.sql.*;public class Main { public static void main(String[] args) { // TODO Auto-generated method stub String driver = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://127.0.0.1:3306/person"; String user ="root"; String password =""; try{ Class.forName(driver); Connection conn=DriverManager.getConnection(url,user,password); if(!conn.isClosed()) System.out.println("Succeed!"); Statement statement = conn.createStatement(); String sql = "select * from student"; ResultSet rs = statement.executeQuery(sql); String name = null; while(rs.next()){ //name = rs.getString("name"); System.out.println("id:"+rs.getString("id")+" "+"name:"+rs.getString("name")); } rs.close(); conn.close(); }catch(ClassNotFoundException e){ System.out.println("sorry,can't find the driver"); e.printStackTrace(); }catch(SQLException e){ e.printStackTrace(); }catch(Exception e){ e.printStackTrace(); } }}
Yes. Two groups of data are retrieved successfully!