public class TestJDBC {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//准备连接参数
String username="root";
String password="密码";
//连接地址
String url="jdbc:mysql://127.0.0.1:3306/要连接的数据库名?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true";
//获取连接对象
Connection connection = DriverManager.getConnection(url, username, password);
//测试是否连接成功;
System.out.println(connection.getCatalog());//获取连接的数据库名
//准备sql语句
String sql="insert into dept values(61,'12312','456')";//增加
String sql1="delete from dept where deptno=60";//删除
String sql2="sql语句";//修改
String sql3="select * from dept";
//准备Statement对象
statement = connection.createStatement();
//发送sql语句
//int i = statement.executeUpdate(放入要执行的语句变量名);//executeUpdate只能用增删改
ResultSet resultSet = statement.executeQuery(sql3);//查
boolean next = resultSet.next();//这是执行一次指针下移查到下一条数据
//get***获取值
int a = resultSet.getInt("主键名");//获取到表的id主键
System.out.println(a);
String dname = resultSet.getString("属性名");
System.out.println(dname);
//例子遍历数据库
while (resultSet.next()){
int deptno = resultSet.getInt("deptno");
System.out.print("deptno="+deptno+" ");
String dname = resultSet.getString("dname");
System.out.print("dname="+dname+" ");
String loc = resultSet.getString("loc");
System.out.println("loc="+loc);
}
//关闭资源;
connection.close();
}
}
Class.forName("com.mysql.cj.jdbc.Driver");
//准备连接参数
String username="root";
String password="123456789";
//连接地址
String url="jdbc:mysql://127.0.0.1:3306/test9?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true";
//获取连接对象
Connection connection = DriverManager.getConnection(url, username, password);
//测试是否连接成功;
System.out.println(connection.getCatalog());//获取连接的数据库名
//关闭资源;
//准备sql语句
connection.close();