###代码示例1:
import java.sql.*;
public class Test {
public static void main(String[]args){
//普通的MySQL数据库连接
/*
try{
Class.forName("com.mysql.jdbc.Driver");
}catch(ClassNotFoundException e){
System.out.println("数据库注册失败!");
}
*/
try{
new com.mysql.jdbc.Driver();
}catch(SQLException e){
System.out.println("数据库注册失败!");
}
Connection con=null;
Statement st=null;
ResultSet rs=null;
try{
con=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/myfirstdb","root","2490248");
st=con.createStatement();
rs=st.executeQuery("select * from dept");
while(rs.next()){
System.out.println(rs.getInt("did"));
System.out.println(rs.getString("dname"));
}
}catch(SQLException e){
}
}
}
代码示例2:
import java.sql.*;
//完美的例子:
public class goodJDBC {
public static void main(String[] args) {
Connection con=null;
Statement st=null;
ResultSet rs=null;
try{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/myfirstdb","root","2490248");
st=con.createStatement();
rs=st.executeQuery("select * from dept");
while(rs.next()){
System.out.println(rs.getInt("did"));
System.out.println(rs.getString("dname"));
}
}catch(ClassNotFoundException e){
e.printStackTrace();
}catch(SQLException e){
e.printStackTrace();
}finally{
try{
if(rs!=null){
rs.close();
rs=null;
}
if(st!=null){
st.close();
st=null;
}
if(con!=null){
con.close();
con=null;
}
}catch(SQLException e){
e.printStackTrace();
}
}
}
}