package com.company;
import java.sql.*;
public class Test {
public static void main(String[] args) {
ResultSet resultSet=null;
PreparedStatement statement=null;
Connection connection=null;
try {
//1加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2创建连接
connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/idea?useSSL=true&characterEncoding=utf-8&user=root&password=root");
//3.写sql语句
//这里为查询操作,查询userinfo表所有信息
String sql="select * from userinfo";
//4.得到statement对象
statement = connection.prepareStatement(sql);
//5.执行sql语句
resultSet = statement.executeQuery();
//增添信息操作为:
//string sql=“insert into 表名 values('值1', '值2',...)";
//statement = connection.prepareStatement(sql);
//resultSet = statement.executeUpdate(sql);
//修改信息操作为:
//string sql = "update 表名 set 列名 = 新值 where 列名 = 某值";
//statement = connection.prepareStatement(sql);
//resultSet = statement.execute(sql);
//删除信息操作为:
//string sql = "delete from 表名 where 条件";
//statement = connection.prepareStatement(sql);
//resultSet = statement.execute(sql);
//6处理结果集
while (resultSet.next()){
System.out.print(" id: "+resultSet.getInt(1));
System.out.print(" username: "+resultSet.getString(2));
System.out.print(" password: "+resultSet.getString(3));
System.out.println("-----------");
}
} catch (Exception e) {
e.printStackTrace();
}finally {
//7关闭资源
if(resultSet!=null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(statement!=null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(connection!=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}