天天看點

mysql簡單資料庫連接配接

package connect;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

public class Connect {

public static void main(String[] args) {

try {

Class.forName(“com.mysql.jdbc.Driver”);

String url=”jdbc:mysql://localhost:3306/kaoshi”;//kaoshi是自己的資料庫

Connection conn=DriverManager.getConnection(url, “root”, “admin”);//自己的使用者名和密碼

System.out.println(“資料庫連接配接成功”);

Statement stm=conn.createStatement();

String sql=”select * from tab_student”;

ResultSet rs=stm.executeQuery(sql);

while(rs.next()){

System.out.println(“姓名:”+rs.getString(“stu_name”)+” 年齡:”+rs.getInt(“stu_age”));

rs.close;

stmt.close();

conn.close();

}

} catch (ClassNotFoundException e) {

e.printStackTrace();

} catch (SQLException e) {

e.printStackTrace();

}finally{

try {

if (stmt!=null) stmt.close();

} catch (SQLException se2) {

}

try {

if (conn!=null) conn.close();

} catch (SQLException se) {

se.printStackTrace();

}

}

System.out.println(“拜拜!”);

}

}

繼續閱讀