Java实现数据库增删改查(新手篇)

// 首先要有 能操作mysql的.jar包才行,https://dev.mysql.com/downloads/connector/j/   选择platform independent 然后下
//载4.4M的zip,解压拿到.jar 放到 ide的包里面去

import java.sql.*;
public class mysql_connect {
    Connection con;
    public Connection getConnection(){
        try {
            Class.forName("com.mysql.cj.jdbc.Driver"); //加载数据库驱动
        }catch (ClassNotFoundException e){
            e.printStackTrace();
        }
        try{
            con=DriverManager.getConnection("jdbc:mysql:"+"//127.0.0.1:3306/my_company_test","root","mysql");
            System.out.println("连接成功");                         //定义链接数据库方法
        }catch (SQLException e){
            e.printStackTrace();
        }
        return con;
    }
    public static void Cha(){
        mysql_connect c=new mysql_connect();
        Connection con =c.getConnection();                      //调用链接数据库
        try{
            Statement  sql = con.createStatement();              // 定义sql语句
            ResultSet res = sql.executeQuery("select * from test");          //获取查询的数据
            res.last();
            int n=res.getRow();                                 //通过指针获取返回数据长度
            System.out.println(n);
            while (res.next()){
                String name=res.getNString("name");
                System.out.println(name);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private static void ZengShanGai() {
        mysql_connect c=new mysql_connect();
        Connection con =c.getConnection();                      //调用链接数据库

        try{
            System.out.println("执行增语句");
            PreparedStatement sql=con.prepareStatement("insert into test (name) values (?)");
            PreparedStatement sql2=con.prepareStatement("insert into test (name) values (?)");
            sql.setString(1,"zhangsan2");
            sql2.setString(1,"lisi");
            sql.executeUpdate();
            sql2.execute();
            con.close();                                       //   断开连接

            System.out.println("执行更改语句");
            PreparedStatement sql22=con.prepareStatement("update test set name=? where name='zhangsan'");
            sql22.setString(1,"zhangsan3");
            sql22.executeUpdate();

            System.out.println("执行删除语句");
            PreparedStatement sql33=con.prepareStatement("delete from test where name=?");
            sql33.setString(1,"zhangsan3");
            sql33.executeUpdate();
            con.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static void main(String args[]){
//        Cha();
        ZengShanGai();

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值