JavaFX连接MySQL的步骤

1.先加载驱动程序

Class.forName("com.mysql.jdbc.Driver");

2.建立连接(前提是将 mysql-connector-java-版本.jar 导入模块的库)

Connection connection = DriverManager.getConnection("mysql的URL","账户","密码");

3.创建mysql执行语句

String sql = " mysql 定义或更新 语句";

//创建statement对象,把sql语法发给MySQL执行
Statement statement = connection.createStatement();
statement.executeUpdate(sql);  //查询用executeQuery

4.处理ResultSet

5.close()方法关闭连接

小编举个栗子

import java.sql.*;

public class test {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        System.out.println("加载Driver类成功。");

        //DengYue是用户名,javabook是数据库名(密码123456)
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/javabook?useSSL=false","DengYue","123456");
        System.out.println("连接MySQL的DengYue账户成功。");

        /** 用MySQL语句
         * 1.创建一个商品goods表,选用适当的数据类型
         * 2.添加2条数据
         * 3.删除表goods*/

        //String  sql =  "create table goods ( id int, name varchar(32),price double,introduce text );";
         String sql = "insert into goods values (1,'OPPO手机',2000,'手机还行');";
        //String sql = "drop table goods;";

        //创建statement对象,把sql语法发给MySQL执行
        Statement statement = connection.createStatement();
        statement.executeUpdate(sql);


        //关闭连接
        statement.close();
        connection.close();
        System.out.println("关闭~");

    }
}

你可能感兴趣的:(java)