假設本地機器中裝有mysql資料庫,該資料庫的root密碼為“111111”,該資料庫中有一張名為“user”的學生資訊表,該表包含3個欄位,分別為INT型的id(學號),VARCHAR型的NAME(姓名),以及DATE型birthday(生日),請撰寫程式,連接資料庫,并將該表中的所有條目,按照學號,姓名和生日的順序輸出到控制臺,
import java.sql.*;
public class text16 {
public static void main(String[] args) throws SQLException {
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
try{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localname:3306/test" ;
String username = "root" ;
String password = "111111" ;
conn=DriverManager.getConnection(url, username, password);
stmt=conn.createStatement();
String sql="select * from user";
rs=stmt.executeQuery(sql);
System.out.println("id | NAME | brithday ");
while(rs.next()) {
int id=rs.getInt("id");
String name=rs.getString("name");
Date brithday=rs.getDate("brithday");
System.out.println("id | NAME | brithday ");
}
}
catch (Exception e) {
e.printStackTrace();
}finally {
if(rs !=null) {rs.close();}
if(stmt !=null) {stmt.close();}
if(conn !=null) {conn.close();}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/239113.html
標籤:其他
