zoukankan      html  css  js  c++  java
  • jdbc java程序连接数据库 案例

    package jdbc;

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.Scanner;

    public class Test {

    public static void main(String[] args) {
    //1.加载驱动
    Connection conn = null;
    Statement sm = null;
    try {
    Class.forName("com.mysql.jdbc.Driver");

    //2.获得数据库连接
    String url = "jdbc:mysql://localhost:3306/epet";

    conn = DriverManager.getConnection(url, "root", "root");

    //3.发送SQL语句,获得结果
    sm = conn.createStatement();
    /*Scanner input = new Scanner(System.in);
    System.out.println("输入狗的名称:");
    String name = input.next();
    System.out.println("输入狗的健康值:");
    int health = input.nextInt();
    System.out.println("输入狗的亲密度:");
    int love = input.nextInt();
    System.out.println("输入狗的品种:");
    String strain = input.next();

    String sql = "INSERT INTO dog(NAME,health,love,strain) VALUES ('"+name+"',"+health+","+love+",'"+strain+"')";
    */
    String updateSql = "update dog set health = 100 where id=1";

    String deleteSql = "delete from dog where id = 1";
    //4.处理结果
    //int count = sm.executeUpdate(sql);
    //int count = sm.executeUpdate(updateSql);
    int count = sm.executeUpdate(deleteSql);
    if(count > 0) {
    //System.out.println("数据插入成功!");
    //System.out.println("数据修改成功!");
    System.out.println("数据删除成功!");
    } else {
    //System.out.println("数据插入失败!");
    //System.out.println("数据修改失败!");
    System.out.println("数据删除失败!");
    }

    //System.out.println("连接成功!");
    } catch (ClassNotFoundException e) {
    e.printStackTrace();
    } catch (SQLException e) {
    e.printStackTrace();
    } finally {
    //5.释放资源
    try {
    conn.close();
    sm.close();
    } catch (SQLException e) {
    e.printStackTrace();
    }

    }



    }

    }

  • 相关阅读:
    2-python数据分析-基于pandas的数据清洗、DataFrame的级联与合并操作
    1-2-python数据分析-DataFrame基础操作巩固-股票分析、双均线策略制定
    1-python数据分析-数据分析三剑客之Pandas基础操作
    单例模式
    装饰器模式
    适配器模式
    es通用工具类ElasticSearchUtil
    ELK+RabbitMq搭建日志系统
    redis能保证数据100%不丢失吗?
    面试官问你redis是单线程还是多线程该怎么回答?
  • 原文地址:https://www.cnblogs.com/dongrilaoxiao/p/6757914.html
Copyright © 2011-2022 走看看