步骤
- 决定和哪个数据库建立连接,即决定把哪个数据库驱动加载进来(这里加的是MySQL的驱动)
- 建立连接
- 把sql语句发送给数据库程序,数据库程序把执行的结果返回
- 断开和数据库的连接并释放资源
代码实现
- 数据库连接
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/数据库名";
String username = "用户名";
String password = "密码";
Connection connection = null;
Statement statement= null;
try {
Class.forName(driver); //classLoader,加载对应驱动
connection = (Connection) DriverManager.getConnection(url, username, password);//建立连接
statement = connection.createStatement();
// 查询
selectTest(connection,statement);
// 增加
insertTest(connection,statement);
// 删除
deleteTest(connection,statement);
// 修改
updateTest(connection,statement);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
finally {
statement.close();
connection.close();
}
- 增加
public static void insertTest(Connection connection,Statement statement){
String sql="insert into Table_1(id,name,date) values(100,100,100)";
try {
int count=statement.executeUpdate(sql);
if(count>0){
System.out.println("insert success");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
- 删除
public static void deleteTest(Connection connection,Statement statement){
String sql="delete from Table_1 where id='100'";
try {
int count=statement.executeUpdate(sql);
if(count>0){
System.out.println("delete success");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
- 查询
public static void selectTest(Connection connection,Statement statement){
String sql="select * from Table_1";
try {
ResultSet rs=statement.executeQuery(sql);
System.out.println("1");
while (rs.next()) {
System.out.println(rs.getInt("id"));
System.out.println(rs.getInt("name"));
System.out.println(rs.getDate("date"));
}
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
- 修改
public static void updateTest(Connection connection,Statement statement){
String sql="update Table_1 set name=44 where id=5";
try {
int count=statement.executeUpdate(sql);
if(count>0){
System.out.println("update success");
}
} catch (SQLException e) {
e.printStackTrace();
}
}