[java]jdbc操作mysql

获取连接, 释放连接

导入mysql driver, 导入druid连接池,导入Dbutils(queryRunner)

public class JdbcUtils {
    private static DataSource dataSource;

    static {
        Properties properties = new Properties();
        InputStream inputStream = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
        try {
            properties.load(inputStream);
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() {
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return conn;
    }

    public static void close(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}

druid连接db

queryForOne
queryForList
queryForSingleValue

update  (Insert/Update/Delete) 返回受影响行数

注意点:

- 正确的
        String sql = "insert into t_book(`name`,`author`,`price`,`sales`,`stock`,`img_path`) values(?,?,?,?,?,?)";

- 错误的
        String sql = "insert into t_book(name ,author ,price ,sales ,stock ,img_path ) values(‘?‘ , ‘?‘ , ? , ? , ? , ‘?‘)";

相关推荐