用JAVA语言查找MySQL数据库里的内容
前题:
1>create database student;
2>create table Students(
ID int,
name char(20));
3>insert into Students(ID,name)values(1,"wang");
java代码:
import java.sql.*;
public class MySqlSelect {
public static void main(String[] args){
Connection conn=null;
Statement ment=null;
ResultSet rset=null;
String cname="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost/student?user=root&password=123456";
try{
Class.forName(cname);
conn=DriverManager.getConnection(url);
ment=conn.createStatement();
rset=ment.executeQuery("select * from Students");
while(rset.next()){
System.out.println(" ID: "+rset.getInt(1)+"; name: "+rset.getString("name"));
}
//rset.getInt(1)是调用数据表中的第一列。rset.getString是调用数据表的name列
}catch(ClassNotFoundException e){
e.printStackTrace();
}catch(SQLException se){
se.printStackTrace();
}finally{
try{
if(rset!=null){
rset.close();
rset=null;
}
if(ment!=null){
ment.close();
ment=null;
}
if(conn!=null){
conn.close();
conn=null;
}
}catch(SQLException e2){
e2.printStackTrace();
}
}
}
}
public class MySqlSelect {
public static void main(String[] args){
Connection conn=null;
Statement ment=null;
ResultSet rset=null;
String cname="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost/student?user=root&password=123456";
try{
Class.forName(cname);
conn=DriverManager.getConnection(url);
ment=conn.createStatement();
rset=ment.executeQuery("select * from Students");
while(rset.next()){
System.out.println(" ID: "+rset.getInt(1)+"; name: "+rset.getString("name"));
}
//rset.getInt(1)是调用数据表中的第一列。rset.getString是调用数据表的name列
}catch(ClassNotFoundException e){
e.printStackTrace();
}catch(SQLException se){
se.printStackTrace();
}finally{
try{
if(rset!=null){
rset.close();
rset=null;
}
if(ment!=null){
ment.close();
ment=null;
}
if(conn!=null){
conn.close();
conn=null;
}
}catch(SQLException e2){
e2.printStackTrace();
}
}
}
}
输出:
ID: 1; name: wang