首页 > 技术文章 > Java——连接MySql数据库

it-mh 2019-07-18 10:18 原文

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语句,此方法通常用于用户提供的交互式查询。

 

推荐阅读