• Java——连接MySql数据库


    eclipse项目文件结构

    /JavaConnMySqlTest/src/db.properties

    jdbc.drivers=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://127.0.0.1:3306/mydemo?serverTimezone=UTC
    jdbc.username=root
    jdbc.password=123456
    

    /JavaConnMySqlTest/src/com/java/mysql/test/TestDB.java

    package com.java.mysql.test;
    
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.sql.*;
    import java.util.Properties;
    
    public class TestDB {
        public static Connection getConnection() throws SQLException,IOException {
            Properties props = new Properties();
            FileInputStream in = new FileInputStream("src/db.properties");//读取数据库配置文件
            props.load(in);
            
            String drivers = props.getProperty("jdbc.drivers");//获取该项值
            if(drivers != null) {
                System.setProperty("jdbc.drivers","drivers");//加载数据库驱动
            }
            String url = props.getProperty("jdbc.url");
            String username = props.getProperty("jdbc.username");
            String password = props.getProperty("jdbc.password");
            
            return DriverManager.getConnection(url, username, password);//建立数据库连接
        }
        
        public static void runTest() throws SQLException,IOException {
            Connection conn = getConnection();//获得一个数据库链接
            
            try {
                Statement stat = conn.createStatement();
                stat.executeUpdate("CREATE TABLE greetings (Message CHAR(20))");
                stat.executeUpdate("INSERT INTO greetings VALUES ('Hello,world!')");
                
                ResultSet result = stat.executeQuery("SELECT * FROM greetings");
                if(result.next()) {
                    System.out.println(result.getString(1));
                }
                result.close();
            }finally {
                conn.close();
            }
        }
        
        public static void main(String[] args) {
            try {
                    runTest();
            }catch(SQLException ex) {
                ex.printStackTrace();
            }catch(IOException ex) {
                ex.printStackTrace();
            }
        }
    
    }

    扩展

    executeUpdate方法可以执行INSERT、UPDATE、DELETE之类的操作,也可以执行CREATE TABLE和DROP TABLE之类的数据定义语句。
    executeQuery方法执行SELECT查询。该方法返回的是一个ResultSet对象。
    execute方法可以执行任意的SQL语句,此方法通常用于用户提供的交互式查询。

  • 相关阅读:
    vue(七)--监听属性(watch)
    vue(六)--计算属性(computed)
    JVM参数配置&&命令工具
    GC回收算法&&GC回收器
    JVM宏观认知&&内存结构
    分布式配置中心Apollo——QuickStart
    了解敏捷开发
    服务链路跟踪 && 服务监控
    数据读写API——IO流
    Nginx+Zuul集群实现高可用网关
  • 原文地址:https://www.cnblogs.com/it-mh/p/11205493.html
Copyright © 2020-2023  润新知