标签:
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class TestJDBC { public static void main(String[] args) { //1. 注册驱动 try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } Connection conn = null; ResultSet set = null; try { //2. 创建一个连接对象 conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mytest","root","123456");
//第一个参数是url,第二个是mysql用户名,第三个是密码。
//3. 创建一个sql语句的发送命令对象 Statement statement = conn.createStatement(); //4. 执行SQL,拿到查询的结果集对象 set = statement.executeQuery("select * from stu"); //5. 输出结果集的数据 while(set.next()){ System.out.println(set.getInt("sid") + " " + set.getString("sname")); } } catch (SQLException e) { e.printStackTrace(); }finally{ //6. 关闭连接,命令对象,结果集 if(set!=null){ try { set.close(); } catch (SQLException e) { e.printStackTrace(); } } if(conn!=null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } }
标签:
原文地址:http://www.cnblogs.com/xiezie/p/5689367.html