JDBC

来源:互联网 发布:网络著作权.司法解释 编辑:程序博客网 时间:2024/06/06 14:05

                     JDBC驱动

package com.hbtt.oop17;


import java.sql.*;
 
public class JDBCTest {

public static void main(String[] args){
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost:3306/myschool";
String user = "root";
String password = "hbtt";
// 1、加载驱动
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("成功加载驱动");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
// 2、建立连接
conn = DriverManager.getConnection(url,user,password);

Statement stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT id,stuName, password, mobile , email, address FROM student");
System.out.println("ID\t姓名\t密码\t手机号\t\te-mail\t\t住址");
while(rs.next()){
int a = rs.getInt("id");
String b = rs.getString("stuName");
String c = rs.getString("password");
String d = rs.getString("mobile");
String e = rs.getString("email");
String f = rs.getString("address");
System.out.println(a+"\t"+b+"\t"+c+"\t"+d+"\t"+e+"\t"+f);
}

} catch (SQLException e) {
e.printStackTrace();
} finally {
// 4、关闭ResultSet、Statement和数据库连接
try {
if (null != rs) {
rs.close();
}
if (null != pstmt) {
pstmt.close();
}
if (null != conn) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

0 0