使用JAVA连接MYSQL5.0
到MYSQL网站下载mysql-connector-java-5.0.4.zip文件,解压。
解压后有一个文件:mysql-connector-java-5.0.4-bin.jar
把mysql-connector-java-5.0.4-bin.jar文件拷贝到%JAVA_HOME%\jre\lib\ext\目录下即可。
什么CLASSPATH之类的都不用设置。
测试背景:mysql有个默认数据库test,我在test数据库下建立表text,只有一个字段:value,字段的类型是text。mysql数据库默认字符设置是utf-8。
测试文件TestConnection.java:
引用:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
import com.mysql.jdbc.*;
public class TestConnection {
public static void main(String[] args){
try{Class.forName("com.mysql.jdbc.Driver");
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost/test?user=cheneylou&password=1234");
Statement stmt= conn.createStatement();
stmt.execute("insert into text values '123' ");
stmt.execute("insert into text values 'UTF8简体中文' ");
ResultSet rs = stmt.executeQuery("select * from text");
while(rs.next()){
System.out.println(rs.getString("value"));
}
rs.close();
conn.close();
} catch( ClassNotFoundException e){System.out.println(e.getMessage());}
catch (SQLException ex){
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}
}
}