package com.cssxt.jdbc;
//用于与Mysql数据库连接测试
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcTest {
public static void main(String[] args) {
Connection conn=null;
Statement st=null;
ResultSet rs=null;
try {
//加载驱动,mysql的驱动名是“com.mysql,jdbc.Driver”
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/test";
String user="root";
String password="123";
//然后是建立连接,注意不同的数据库的url是不同的
conn=DriverManager.getConnection(url, user, password);
if(!conn.isClosed()){
System.out.println("成功连接数据库");
}
st=conn.createStatement();
String sql="select * from emp";
//查询语句返回结果集
rs=st.executeQuery(sql);
while(rs.next()){
System.out.print("编号:"+rs.getInt("empno")+"/t");
System.out.println("姓名:"+rs.getString("ename"));
}
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally{
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}finally{
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}finally{
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
}