Eclipse中用jdbc连接数据库插入删除的代码

mysql-connector-java-5.1.44-bin.jar的链接:
https://pan.baidu.com/s/1VfsXgJqxGSetGpror-agIA

package link;
import java.sql.*;
import java.util.*;


public class insert {
    public static void main(String args[]) {
        //连接数据源
        //声明Connection对象
        Connection con=null;
        //驱动程序名
        String driver ="com.mysql.jdbc.Driver";
        //URL指向要访问的数据库名mydata 
        String url = "jdbc:mysql://xxxxxxx:3306/表的名字?user=用户名&password=密码&useUnicode=true&characterEncoding=UTF8&useSSL=true"; 

        //MySQL配置时的用户名和密码
        //String user = "xxx";
        //String password = "xxx";
        //便利查询结果集
        try {
            //加载驱动程序:通过java.lang.Class类的静态方法forName(String className)实现,加载想要连接的数据库的驱动到JVM(Java虚拟机)
            //成功加载后,会将Driver类的实例注册到DriverManager类中
            Class.forName(driver);
            //1.getConnection()方法,连接MySQL数据库
            //连接URL定义了连接数据库时的协议、子协议、数据源标识,书写形式:协议:子协议:数据源标识
            con=DriverManager.getConnection(url); //user,password
            if(!con.isClosed()) System.out.println("Succeeded connecting to the Database!");
            //2.创建statement类对象,用来执行SQL语句    
             Statement statement = con.createStatement();


             //System.out.println("-------------");
             //System.out.println("姓名");

             //插入名字
             String sql="insert into 表的名字(表的表头) values('...插入的东西')";        
             statement.executeUpdate(sql);//执行sql语句
             System.out.println("插入到数据库成功");

             //删除名字
             //String sql="delete from t_first_table where name='...'";
             //statement.executeUpdate(sql);




            //3.ResultSet类,用来存放获取的结果集
             String name=null;
            ResultSet rs = statement.executeQuery("SELECT * FROM 表的名字");
             while(rs.next()) {
                 //获取数据
                 name=rs.getString("name");
                System.out.println(name);
                            }    
             rs.close();
             con.close();
            }
        catch(ClassNotFoundException e) {   
            //数据库驱动类异常处理:找不到驱动程序类 ,加载驱动失败
            System.out.println("Sorry,can`t find the Driver!");   
            e.printStackTrace();   
            }
        catch(SQLException e) {
            //数据库连接失败异常处理
            e.printStackTrace();  
            }
        catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        finally{
            System.out.println("数据库数据成功获取!!");
        }

 }  
}
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Laura_Wangzx

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

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

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

打赏作者

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

抵扣说明:

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

余额充值