driverClassName = com.mysql.jdbc.Driver url = jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull username = root password = 123456
package com.chen.learn.utils; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; /** * mysql數據庫鏈接工具類 * * @author chenxiaoyu * @email 1524904743@qq.com * @date 2016年9月8日 上午10:22:45 * @package com.chen.learn.utils * */ public class JdbcUtils { private static Properties prop; //靜態代碼塊,只在加載運行一次 static { //加載配置文件 InputStream io = JdbcUtils.class.getClassLoader().getResourceAsStream("dbConfig.properties"); //讀取配置文件內容到properties對象中 prop = new Properties(); try { prop.load(io); //加載驅動類 Class.forName(prop.getProperty("driverClassName")); } catch (IOException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } /** * 獲取mysql數據庫鏈接 * @return */ public static Connection getConnection() { Connection con = null; try { con = DriverManager.getConnection(prop.getProperty("url"), prop.getProperty("username"), prop.getProperty("password")); } catch (SQLException e) { throw new RuntimeException(e); } return con; } }
利用上面寫好的工具類來獲取鏈接,而後進行增改查的操做,具體步驟看代碼,java
/** * 測試 * prep.execute()能夠執行修改、添加和刪除語句,其返回值是boolean類型 * 返回true:表示執行的是查詢語句,可使用getResultSet()獲取查詢到的ResultSet對象 * 返回false:表示執行的是修改、添加和刪除的語句,可使用getUpdateCount()獲取受影響的記錄條數 */ @Test public void testJdbc() { Connection con = JdbcUtils.getConnection(); //sql模板,增、改、查 // String sql = "insert into userinfo(username, password, sex, age, create_time) values(?, ?, ?, ?, NOW())"; // String sql = "update userinfo set username = ?, password = ?, sex = ?, age = ?, create_time = NOW() where id = ?"; String sql = "select * from userinfo where deleted = 0 and username = ?"; try { //預編譯sql語句 PreparedStatement prep = con.prepareStatement(sql); //爲上面的sql模板填充參數 prep.setString(1, "小黃"); // prep.setString(2, "abc123"); // prep.setString(3, "女"); // prep.setInt(4, 22); // prep.setInt(5, 15); //執行sql語句 boolean result = prep.execute(); if (result) { ResultSet a = prep.getResultSet(); while (a.next()) { System.out.println(a.getString("username") + " ======== " + a.getString("password")); if (a.isLast()) { return; } } }else { int a = prep.getUpdateCount(); System.out.println(a); } } catch (Exception e) { throw new RuntimeException(e); } }
-------第一次寫技術博客,感受思路很混亂......有不對的地方請指正!mysql