MySQL的安装 可视化工具 JDBC的增删改查

时间:2022-02-12 04:59:42

1.Mysql和可视化工具的安装

安装包网上有很多资源。这里推荐一个我一直在用的学习网站,上面有提供安装包和详细的说明。

http://how2j.cn/k/mysql/mysql-install/377.html

 

2.JDBC的使用 简单的增删改查

首先要导入一个jar包。

下载地址:

http://how2j.cn/frontdownload?bean.id=224

import com.mysql.jdbc.Connection;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBC {
    public static void main(String[] args) {
        Statement statement = null;
        Connection connection = null;
        try {
            //固定写法
            Class.forName("com.mysql.jdbc.Driver");
            //连接Mysql(how2java是数据库名称,root是mysql的账号,admin是密码)
            connection = (Connection) DriverManager.getConnection("jdbc:mysql://127.0.0.1/how2java?characterEncoding=UTF-8", "root", "admin");
            System.out.println("数据库连接成功!"   connection);
            //创建Statement,用于执行SQL语句
            statement = connection.createStatement();
            System.out.println("获取Statement对象"   statement);
            //执行一条SQL语句
            //增删改都可以调用这个方法。只是SQL语句变一下
            String sql = "insert into hero values(null,"   "‘剑圣‘"   ","   415.0f   ","   100   ")";
            statement.execute(sql);
            System.out.println("插入成功!");
            //执行SQL查询功能
            String sql2 = "select * from hero";
            // 执行查询语句,并把结果集返回给ResultSet
            ResultSet rs = statement.executeQuery(sql);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //最后,先关闭statement,再关闭连接
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}