java mysql 示例
一、登陆mysql;创建账号允许远程访问
-- 创建用户
CREATE USER 'user'@'%' IDENTIFIED BY 'password';
-- 授予远程访问权限
GRANT ALL PRIVILEGES ON *.* TO 'user'@'%' WITH GRANT OPTION;
二、关闭防火墙
sudo ufw disable
三、下载jar包,并解压
# 解压jar包
jar xf mysql-connector-java-8.0.26.jar
四、代码
import java.sql.*;
class JavaMysqlConnection{public static void main(String args[]){try{Class.forName("com.mysql.cj.jdbc.Driver");System.out.println("====");Connection connect=DriverManager.getConnection("jdbc:mysql://ip:3306/db","user","password");System.out.println("====");Statement stmt=connect.createStatement();ResultSet rs=stmt.executeQuery("select * from data");while(rs.next())System.out.println(rs.getString(1)+" "+rs.getInt(2)+" "+rs.getString(3));connect.close();}catch(Exception e){ System.out.println(e);}}
}
执行
java -cp /home/${user}/.m2/repository/mysql/mysql-connector-java/8.0.26 test.java