新建一个MyJdbc的class:
package cn.itcast.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Statement;
public class Jdbc {
public static void main(String[] args) throws Exception{
template();
}
static void template() throws Exception{
String url = "jdbc:mysql://localhost:3306/jdbc";
String user = "root";
String password = "123";
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
//注册驱动
Class.forName("com.mysql.jdbc.Driver");
//建立连接
conn = DriverManager.getConnection(url, user, password);
//创建语句,装载数据的车
st = (Statement) conn.createStatement();
//执行语句,sql语句
rs = st.executeQuery("select * from user");
//处理结果
while(rs.next()){
System.out.println(rs.getObject(1) + "\t" + rs.getObject(2)
+ "\t" + rs.getObject(3) + "\t" + rs.getObject(4));
}
} finally {
try{ //关闭通道
if(rs != null)
rs.close();
}finally{
try{
if(st != null)
st.close();
}finally{
if(conn != null)
conn.close();
}
}
}
}
}