码迷,mamicode.com
首页 > 数据库 > 详细

[java]jdbc操作mysql

时间:2020-05-03 10:41:57      阅读:80      评论:0      收藏:0      [点我收藏+]

标签:eval   drive   str   single   except   连接   mysq   stat   owa   

获取连接, 释放连接

导入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(‘?‘ , ‘?‘ , ? , ? , ? , ‘?‘)";

[java]jdbc操作mysql

标签:eval   drive   str   single   except   连接   mysq   stat   owa   

原文地址:https://www.cnblogs.com/iiiiiher/p/12820812.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!