import java.beans.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Driver;
public class Base {
public static void main(String[] args) throws SQLException {
//数据库连接对象
Connection conn = null;
//数据库操作对象
java.sql.Statement stmt = null;
//结果集
ResultSet rs = null;
//1.注册驱动
Driver driver = new com.mysql.jdbc.Driver();
DriverManager.registerDriver(driver);
//2.获取数据库连接
String url = "jdbc:mysql://localhost:3306/hellosele";
String user = "root";
String passwd = "123456";
conn = DriverManager.getConnection(url,user,passwd);
//3.获取数据库操作对象
stmt =conn.createStatement();
//4.执行SQL语句:DQL语句
String sql = "select * from student";
rs = stmt.executeQuery(sql);
//5.处理查询结果集
while(rs.next()){
String sno = rs.getString("sno");
String sname = rs.getString("sname");
String major = rs.getString("major");
System.out.println(sno+"\t"+sname+"\t"+major);
}
rs.close();
stmt.close();
conn.close();
}
}
注册驱动的第二种方式:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Driver;
import com.mysql.jdbc.Statement;
public class Base {
public static void main(String[] args) throws SQLException {
Connection conn = null;
java.sql.Statement stmt = null;
ResultSet rs = null;
try {
// 1.第二种注册驱动:利用java的反射机制
Class.forName("cn.dasyou.jdbctest.RegisterDriver");
//1.第三种注册驱动:SUN公司自带
Class.forName("com.mysql.jdbc.Driver");
// 2.获取数据库连接
String url = "jdbc:mysql://127.0.0.1:3306/hellosele";
String user = "root";
String passwd = "123456";
conn = DriverManager.getConnection(url, user, passwd);
// 3.获取数据库操作对象
stmt = conn.createStatement();
// 4.执行SQL语句
String sql = "select * from student";
rs = stmt.executeQuery(sql);
//处理查询结果集
while(rs.next())
{
String sno = rs.getString("sno");
String sname = rs.getString("sname");
String major = rs.getString("major");
System.out.println( sno+ " " + sname + " " + major);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//关闭资源
if(rs != null)
{
rs.close();
}
if(stmt != null)
{
stmt.close();
}
if(conn != null)
{
conn.close();
}
}
}
}
/**
- 注册驱动
*/
class RegisterDriver {
static {
try {
System.out.println("sss");
Driver driver = new com.mysql.jdbc.Driver();
DriverManager.registerDriver(driver);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
网友评论