Java语言关于数据库的基本操作

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();
                }
            }

        }

    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值