java jdbc连接mysql实战

1.下载JDK和jar包
JDK
mysql-connector-java-5.1.47.jar
2,将mysql-connector-java-5.1.47.jar放在JDK/lib目录下并设置环境变量
 vi .bash_prifile 
export JAVA_HOME=/home/mysql/liys/jdk64/
export CLASSPATH=.:$JAVA_HOME/jre/lib/rt.jar:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar:$JAVA_HOME/lib/mysql-connector-java-5.1.47.jar
export PATH=$PATH:$JAVA_HOME/bin

注意:一定要将mysql-connector-java-5.1.47.jar加到CLASSPATH里,不让编译后执行的时候会报:
[mysql@t3-dtpoc-dtpoc-web04 liys]$ /home/mysql/liys/jdk64/bin/java MySQLJDBCExample
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
        at java.lang.Class.forName(Class.java:256)
        at MySQLJDBCExample.main(MySQLJDBCExample.java:9)
        
3.编写conn程序
[mysql@t3-dtpoc-dtpoc-web04 liys]$ pwd
/home/mysql/liys
[mysql@t3-dtpoc-dtpoc-web04 liys]$ vi MySQLJDBCExample.java
import java.sql.*;
public class MySQLJDBCExample {
    public static void main(String[] args) {
        String url = "jdbc:mysql://127.0.0.1:3306/mytest";
        String user = "root";
        String password = "1234";

        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection connection = DriverManager.getConnection(url, user, password);
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery("SELECT * FROM join_test1");

            while (resultSet.next()) {
                                
                int column1 = resultSet.getInt("id");
                String column2 = resultSet.getString("name1");
                 System.out.println(column1 + " " + column2);
            }
            resultSet.close();
            statement.close();
            connection.close();
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }
}
        
4.编译程序后执行:        
[mysql@t3-dtpoc-dtpoc-web04 liys]$ /home/mysql/liys/jdk64/bin/javac MySQLJDBCExample.java
[mysql@t3-dtpoc-dtpoc-web04 liys]$ /home/mysql/liys/jdk64/bin/java MySQLJDBCExample                                    
Wed Sep 27 10:31:03 CST 2023 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
1 test1_1
3 test1_3
4 test1_4
5 test1_5
2 test1_2
[mysql@t3-dtpoc-dtpoc-web04 liys]$     

你可能感兴趣的:(python,android,开发语言)