package com.usky.practice03.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MyConntction {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet res =null;
String sql =null;
String url = null;
String username = null;
String password = null;
try {
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
//连接mysql的url 3306为mysql端口号 test 为数据库名称 后面的是设置字符集编码
url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8";
//用户名
username = "root";
//密码
password="root";
//与mysql建立连接
conn=DriverManager.getConnection(url,username,password);
sql = "select * from user";
//设置事物提交为手动
conn.setAutoCommit(false);
stmt =conn.createStatement();
//执行语句
res=stmt.executeQuery(sql);
//循环遍历结果集
while(res.next()){
System.out.println(res.getString("username"));
}
//事物提交
conn.commit();
} catch (Exception e) {
try {
//事物回滚
conn.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
e.printStackTrace();
}
finally{
if(stmt!=null){
try {
//关闭资源
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null){
try {
//关闭资源 释放连接
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
输出结果为:
zhangsan
lisi
wangwu