JDBC简介
JDBC驱动程序_百度百科
前段时间学了jdbc,通过java中jdbc.driver这个类,实现java与mysql之间的交互,以下为学习笔记,笔记省略mysql安装教程(网上一搜一大把,我也懒的写)
下载、导入Jar包
MySQL :: MySQL Product Archives
这个链接是mysql的档案界面,如图,选择connector/j

选择Archives,进入选择版本界面,选择你安装的mysql版本,我这里选择5.1.22,显示如下图界面

选择一个下载,只是压缩格式不同,如果没有第三方压缩软件,就选下面这个,微软自带的解压软件不支持tar.gz格式
下载后解压,在压缩包中找到mysql-connector-java-(版本号)-bin.jar,这就是我们要用的jar包。
打开你的java编译器,这里以IDEA为例,在项目根目录下新建lib文件夹,把刚刚的jar文件拖进去,右击文件夹,选择add as library(eclipse操作相同,用记事本的建议还是弄一个编译器吧)。

到了这一步,恭喜你完成了jar包的引入
代码示例
以下为我项目中的一个Db工具类示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
| import java.io.IOException; import java.io.InputStream; import java.sql.*; import java.util.Properties;
public class DBUtils { private static final Properties PROP =new Properties(); private static ThreadLocal<Connection> threadLocal=new ThreadLocal<>(); static { InputStream is = DBUtils.class.getResourceAsStream("/db.properties"); try { PROP.load(is); Class.forName(PROP.getProperty("driver")); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } }
public static Connection getConnection(){ Connection connection=threadLocal.get(); try { if(connection==null){ connection= DriverManager.getConnection(PROP.getProperty("url"),PROP.getProperty("username"),PROP.getProperty("password")); threadLocal.set(connection); } } catch (SQLException e) { throw new RuntimeException(e); } return connection; } public static void begin(){ Connection connection=null; try { connection=getConnection(); connection.setAutoCommit(false); } catch(Exception e) { e.printStackTrace(); } } public static void commit(){ Connection connection=null; try { connection=getConnection(); connection.commit(); } catch (SQLException throwables) { throwables.printStackTrace(); }finally { closeAll(connection,null,null); } } public static void rollback(){ Connection connection=null; try { connection=getConnection(); connection.rollback(); } catch (SQLException throwables) { throwables.printStackTrace(); }finally { closeAll(connection,null,null); } } public static void closeAll(Connection connection, Statement statement, ResultSet resultSet){ try { if(connection!=null){ connection.close(); }else if(statement!=null){ statement.close(); }else if(resultSet!=null){ resultSet.close(); threadLocal.remove(); } } catch (SQLException e) { throw new RuntimeException(e); } } }
|
接下来是properties文件示例写法
1 2 3 4
| driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/mysql2?useUnicode=true&characterEncoding=utf8 username=root password=1234
|
以上为本文内容