1, create the Mysql.properties file in the root directory, use this file is to facilitate the subsequent generation of class files can be modified link any database
2, import jar package, self-Baidu download.
3, write a sqlutil.class (SQL Tool Class)
Package Com.sogood.util;import Java.io.ioexception;import Java.sql.*;import Java.util.properties;public class Sqlutil {private static String username; private static String password; private static String URL; static {Properties pps = new Properties (); try {pps.load (SqlUtil.class.getResourceAsStream ("/com/sogood/mysql.properties")); Username = Pps.getproperty ("username"); Password = pps.getproperty ("password"); url = pps.getproperty ("url"); } catch (IOException e) {e.printstacktrace (); }} public static Connection getconnection () {Connection con = null; try {class.forname ("com.mysql.jdbc.Driver"); con = drivermanager.getconnection (URL, username, password);//Create Data connection} catch (SQLException e) {e.prints Tacktrace (); SYSTEM.OUT.PRINTLN ("Database connection failed"); } catch (ClassNotFoundException e) {throw new RuntimeexcEption ("Driver class not found"); } return con; public static void Close (Connection con, Statement stm, ResultSet rs) {if (rs! = null) {try { Rs.close (); } catch (SQLException e) {e.printstacktrace (); }} if (STM! = null) {try {stm.close (); } catch (SQLException e) {e.printstacktrace (); }} if (con! = null) {try {con.close (); } catch (SQLException e) {e.printstacktrace (); } } }}
4, write a Demo.class class test
1 PackageCom.sogood.jdbc;2 3 ImportCom.sogood.util.SqlUtil;4 5 Importjava.sql.Connection;6 ImportJava.sql.ResultSet;7 Importjava.sql.SQLException;8 Importjava.sql.Statement;9 Ten Public classDemo { One Public Static voidMain (string[] args)throwsSQLException { A query (); - } - the Private Static voidquery () { -Connection con =NULL; -Statement stm =NULL; -ResultSet rs =NULL; + Try { -Con =sqlutil.getconnection (); +String sql = "SELECT * FROM STUDENT"; ASTM =con.createstatement (); atrs =stm.executequery (SQL); -SYSTEM.OUT.PRINTLN ("Query result:"); - while(Rs.next ()) { - intid = rs.getint ("id"); -SYSTEM.OUT.PRINTLN ("id =" +ID); - } in}Catch(Exception e) { - e.printstacktrace (); to}finally { + sqlutil.close (Con, STM, RS); - } the } *}
JDBC, using the properties file to save the database account password and links