1 Download Install connector/j,:http://www.mysql.com/products/connector/. Connector/j is a JDBC driver package developed specifically for MySQL.
2 Add the Classpath under the installation folder mysql-connector-java-5.1.36-bin.jar to the environment variable. Or add the Java Build Path to the project.
3 Steps for basic JDBC programming:
- Load Driver
The methods used are Class.forName() either
Class.forName().newInstance()Or
new DriverName()
- Connecting to a database
DriverManager.getConnection()
- Run the SQL statement
Connection.CreateStatement()
Statement.executeQuery()
Statement.executeUpdate()
- Get result set
while(rs.next())
- Show data
Convert various types in a database to type () methods in Java getXXX
- Shut down
close the resultset
close the statement
close the connection
Instance:
PackageMsImportJava.sql.Connection;ImportJava.sql.DriverManager;ImportJava.sql.SQLException;ImportJava.sql.Statement;ImportJava.sql.ResultSet; Public class testmysql { Public Static void Main(string[] args) {ResultSet rs =NULL; Statement stmt =NULL; Connection conn =NULL;Try{Class.forName ("Com.mysql.jdbc.Driver");//Create an instance of the class identified by the stringString URL ="Jdbc:mysql://localhost:3306/test";//Identify a driver for a noteString user ="Root"; String pwd =""; conn = drivermanager.getconnection (URL, user, pwd); stmt = Conn.createstatement (); String query ="SELECT * from person where age >"; rs = stmt.executequery (query); while(Rs.next ()) {String id = rs.getstring ("id"); String name = Rs.getstring (2);intAge = Rs.getint ("Age"); System.out.println (ID +"\ T"+ name +"\ T"+ age); } }Catch(ClassNotFoundException e) {E.printstacktrace (); }Catch(SQLException e) {E.printstacktrace (); }finally{Try{if(rs! =NULL) {rs.close (); }if(stmt! =NULL) {stmt.close (); }if(Conn! =NULL) {conn.close (); } }Catch(SQLException e) {E.printstacktrace (); } } }}
Preprocessing statements for PreparedStatement:
"insert into person values(?,?
,?)";PreparedStatement pstmt = conn.prepareStatement(sql);pstmt.setString(1"005");pstmt.setString(2"Zhao");pstmt.setInt(318);pstmt.executeUpdate();
Batch processing of statement statements:
Statement stmt = Conn.createstatement (); Stmt.addbatch (" Insert into person values(' 006 ', ' Zeng ', ')'); Stmt.addbatch ("insert into" values(' 007 ', ' Liu ', ) stmt.addbatch ("insert into the person values(' 008 ', ' Zeng '); Stmt.executebatch ();
Batch processing of PreparedStatement statements
String sql =INSERT into person values (?,?,?);PreparedStatement PSTMT = conn. Preparestatement(SQL);Pstmt. setString(1,"006");Pstmt. setString(2,"Zeng");Pstmt. Setint(3, -);Pstmt. setString(1,"007");Pstmt. setString(2,"Liu");Pstmt. Setint(3, -);Pstmt. setString(1,"008");Pstmt. setString(2,"Zeng");Pstmt. Setint(3, -);Pstmt. Executeupdate();
Java Connection MySQL Database