JDBC
时间:2021-07-01 10:21:17
帮助过:4人阅读
jdbc;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
public class JDBCTest {
/**
* 数据库URL
*/
static final String DB_URL = "jdbc:mysql://localhost/demo?user=root&password=root"
;
public static void main(String[] args) {
Connection conn =
null;
Statement stmt =
null;
PreparedStatement psmt =
null;
ResultSet rs =
null;
try {
//获取数据库连接的三种方式
//方式一,推荐该方式,首选方法,作为 DriverManager工具的替代
MysqlDataSource mysqlDataSouurce =
new MysqlDataSource();
mysqlDataSouurce.setUrl(DB_URL);
conn =
mysqlDataSouurce.getConnection();
//方式二
// Class.forName("com.mysql.jdbc.Driver");
// conn = DriverManager.getConnection(DB_URL);
//方式三
// Driver mysqlDriver = new com.mysql.jdbc.Driver();
// DriverManager.registerDriver(mysqlDriver);
// conn = DriverManager.getConnection(DB_URL);
//事务相关
conn.setAutoCommit(
false);
//插入数据,使用executeUpdate
psmt = conn.prepareStatement("insert into user(name, address) values (?, ?)"
);
psmt.setString(1, "user001"
);
psmt.setString(2, "HangZhou"
);
psmt.executeUpdate();
// Statement,不接受参数
stmt =
conn.createStatement();
//查询数据,使用executeQuery
rs = stmt.executeQuery("SELECT id, name, address FROM user"
);
// 获取SQL执行结果
while (rs.next()) {
long id = rs.getLong("id"
);
String name = rs.getString("name"
);
String address = rs.getString("address"
);
System.out.print("ID: " + id + ", Name: " + name + ", Address: " + address + "\n"
);
}
conn.commit();
conn.setAutoCommit(true);
} catch (SQLException se) {
try {
conn.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
se.printStackTrace();
} catch (Exception e) {
try {
conn.rollback();
} catch (SQLException e2) {
e.printStackTrace();
}
e.printStackTrace();
} finally {
// 关闭资源
try {
if (rs !=
null) {
rs.close();
}
} catch (SQLException se1) {
}
try {
if (stmt !=
null)
stmt.close();
} catch (SQLException se2) {
}
try {
if (psmt !=
null)
psmt.close();
} catch (SQLException se3) {
}
try {
if (conn !=
null)
conn.close();
} catch (SQLException se4) {
se4.printStackTrace();
}
}
}
}
JDBC
标签:mysql while create man java语言 sele lex ring cat