mysql JDBC QA

编程入门 行业动态 更新时间:2024-10-09 04:16:33

<a href=https://www.elefans.com/category/jswz/34/1771279.html style=mysql JDBC QA"/>

mysql JDBC QA

1.使用JDBC连接MySql时出现:The server time zone value ‘�й���׼ʱ��’ is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration 在连接字符串后面加上?serverTimezone=UTC

其中UTC是统一标准世界时间。

完整的连接字符串示例:jdbc:mysql://localhost:3306/test?serverTimezone=UTC

或者还有另一种选择:jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8,这个是解决中文乱码输入问题,当然也可以和上面的一起结合:jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC

如何创建JDBC连接?

	JDBC是Java为了链接数据库,定制的一套标准
2.什么是驱动?各大数据厂商根据JDBC接口实现的实现类的集合
3.原生态链接JDBC需要哪些步骤?3.1注册驱动(DriverManager.registerDriver(new Driver())) com.mysql.jdbc.Driver3.2获取链接对象 DriverManager.getConnection() Connection(java.sql)3.3创建执行SQL语句的对象 connection.createStatement() Statement3.4执行SQL语句 executeQuery() 执行查  executeUpdate() 执行增删改3.5如果执行查,返回处理结果集(ResultSet) 执行增删改 (int 执行以后受影响的行数)3.6关流并释放资源
4.第一改进:注册驱动进行改进——如果直接用DriverManager.registerDriver(new Driver())会创建两个驱动对象,使用反射的方法,对Driver进行初始化,初始化会执行静态代码块,静态代码块中有注册语句,这样避免多个驱动对象
5.第二改进:每次执行语句前都会进行注册操作——将注册驱动及获取当前会话链接放置静态代码块中
6.第三改进:将硬编码改为配置编码,使用配置文件记录Driver的全类名,URL,USER,PASSWORD

最终改进:使用德鲁伊连接池(pool = DruidDataSourceFactory.createDataSource(properties))
每次使用时只需pool.getCollection()即可获取连接.为了使用方便可将这几步写进一个JDBC工具类中.

public class JDBCUtil {static  DataSource pool;static{try {Properties properties = new Properties();properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("druid.properties"));pool = DruidDataSourceFactory.createDataSource(properties);} catch (IOException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}}public static Connection getConnection(){try {return pool.getConnection();} catch (SQLException e) {throw new RuntimeException("创建连接对象失败");}}
}

执行SQL语句常用方法

1.DButil

QueryRunner queryRunner = new QueryRunner();
List dbUsers = queryRunner.query(connection, sql, new BeanListHandler< List<T> >(T.class));

注:T是一个Javabean自定义类,这个类的成员变量要与读取的表字段一一对应.

2.PreparedStatement无返回值

PreparedStatement pr =
conn.prepareStatement(“INSERT INTO table VALUES (?,?,?,?,?)”);

3.PreparedStatement有返回值

PreparedStatement pr = connection.prepareStatement(“SELECT * FROM table WHERE column = ?”);
pr.setString(1,*);
ResultSet resultSet = pr.executeQuery();
while (resultSet.next()) {
result = resultSet.getInt(1);
}

更多推荐

mysql JDBC QA

本文发布于:2024-02-27 19:05:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1765980.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:mysql   JDBC   QA

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!