JDBC连接数据库

2 篇文章 0 订阅
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();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码猿人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值