5 写代码测试连接
import java.sql.*;
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
try{
runTest();
}
catch(SQLException e){
for(Throwable t:e)
t.printStackTrace();
}
catch(IOException ex){
ex.printStackTrace();
}
}
public static void runTest()throws SQLException,IOException{
Connection con=getConnection();
try{
Statement stat=con.createStatement();
stat.executeUpdate("create table Greetings(Message CHAR(20))");
stat.executeUpdate("insert into Greetings values('Hello,world')");
ResultSet result=stat.executeQuery("select * from Greetings");
if(result.next())
System.out.println(result.getString(1));
result.close();
// stat.executeUpdate("drop table Greetings");
}
finally{
con.close();
}
}
private static Connection getConnection() throws SQLException,IOException {
Properties props=new Properties();
props.put("user","root");
props.put("password","catherine");
return DriverManager.getConnection("jdbc:mysql://localhost:3306/JDBCTest","root","catherine");
}
}
6.驱动程序配置
如果JDBC驱动程序没有加入到jre中去会导致报错,无法找到相关驱动driver
我们将下载的mysql-connector-java-5.1.15-bin.jar
复制到java_home目录下面,
打开glassfish-3.0.1>glassfish>domains>domain1>lib,如果此目录下没有MySQL的驱动器则把jar包再复制一份贴到这里来。
再编译刚刚的源程序,成功了。
并且成功创建了Greetings表,里面有一条记录Hello,world