JDBC连接MySQL
JDBC连接MySQL
加载及注册JDBC驱动程序
Class.forName("com.mysql.jdbc.Driver");
Class.forName("com.mysql.jdbc.Driver").newInstance();
JDBC URL 定义驱动程序与数据源之间的连接
标准语法:
<protocol(主要通讯协议)>:<subprotocol(次要通讯协议,即驱动程序名称)>:<data source identifier(数据源)>
MySQL的JDBC URL格式:
jdbc:mysql//[hostname][:port]/[dbname][?param1=value1][¶m2=value2]….
示例:jdbc:mysql://localhost:3306/sample_db?user=root&password=your_password
常见参数:
user 用户名
password 密码
autoReconnect 联机失败,是否重新联机(true/false)
maxReconnect 尝试重新联机次数
initialTimeout 尝试重新联机间隔
maxRows 传回最大行数
useUnicode 是否使用Unicode字体编码(true/false)
characterEncoding 何种编码(GB2312/UTF-8/…)
relaxAutocommit 是否自动提交(true/false)
capitalizeTypeNames 数据定义的名称以大写表示
建立连接对象
String url="jdbc:mysql://localhost:3306/sample_db?user=root&password=your_password";
Connection con = DriverManager.getConnection(url);
建立SQL陈述式对象(Statement Object)
Statement stmt = con.createStatement();
执行SQL语句
示例:
Java类型和SQL类型 技术手册P421
PreparedStatement(预编语句)
PreparedStatement stmt = conn.prepareStatement("insert into test(id,name)values(?,?)");
stmt.setInt(1,id);
stmt.setString(2,name);
注:一旦设定语句的参数值后,就可以多次执行改语句,直到调用clearParameters()方法将他清除为止
CallableStatement(预储程序)技术手册P430
JDBC2.0使用
ResultSet对象中的光标上下自由移动
Statement stmt = con.createStatement (ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rs=stmt.executeQuery("select * from test");
public Statement createStatement(int resultSetType,int resultSetConcuttency) throws SQLException
resultSetType
TYPE_FORWARD_ONLY 只能使用next()方法。
TYPE_SCROLL_SENSITIVE 可以上下移动,可以取得改变后的值。
TYPE_SCROLL_INSENSITIVE 可以上下移动。
resultSetConcuttency
CONCUR_READ_ONLY 只读
CONCUR_UPDATABLE ResultSet对象可以执行数据库的新增、修改、和移除
直接使用ResultSet对象执行更新数据
新增数据
更新数据
删除数据
批处理
JNDI-数据源(Data Source)与连接池(Connection Pool)
Tomcat的JDBC数据源设置 技术手册P439
连接池工具-Proxool Var 0.8.3 技术手册P446
设置web.xml
配置Proxool.properties
使用Proxool连接池
感谢阅读此文,希望能帮助到大家,谢谢大家对本站的支持!
SQL查询语句优化的实用方法总结
Mysql使用索引实现查询优化
-
MySQL数据库优化技术之配置技巧总结
-
Linux上通过binlog文件恢复mysql数据库详细步骤
-
Mysql5.7.11在windows10上的安装与配置(解压版)
-
MySQL中实现插入或更新操作(类似Oracle的merge语句)
-
MySQL与Mongo简单的查询实例代码
-
MySql 5.7.14 解压版安装步骤详解
-
MySQL中interactive_timeout和wait_timeout的区别
-
Centos 6.5 下安装mysql 5.6.21的方法
-
MySQL外键使用及说明详解
-
Mysql 下中文乱码的问题解决方法总结