Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.sql.*;
- /**
- *
- * @author 林哲宏
- */
- public class TrySQL {
- public void example(){
- Connection conn=null;
- Statement stmt=null;
- ResultSet rs=null;
- //url格式為 jdbc:mysql://[主機名稱]:[PORT]/[DATABASE]?[user=xxxx&password=xxxx]
- String sql_url="jdbc:mysql://sql12.freemysqlhosting.net:3306/sql12234392?"+"user=ccccccc&password=ccccccc";
- try{
- Class.forName("com.mysql.jdbc.Driver").newInstance();
- conn=DriverManager.getConnection(sql_url);
- stmt=conn.createStatement();
- rs=stmt.executeQuery("SELECT * FROM user");
- //rs的next方法會讓指針在ResultSet上移動,呼叫getXXX("欄位名稱")可以得到相對應的值
- if(rs.next()){
- System.out.println("name:"+rs.getString("name"));
- System.out.println("password:"+rs.getString("pass"));
- }
- System.out.println("查詢成功");
- }catch(Exception e){
- System.out.println("確認使用者SQL查詢出錯");
- e.printStackTrace();
- }finally{
- //最後關掉所有連結
- try{
- if(rs != null){
- rs.close();
- }
- if(stmt != null){
- stmt.close();
- }
- if(conn != null){
- conn.close();
- }
- }catch(SQLException e){
- System.out.println("關閉SQL連結出錯");
- e.printStackTrace();
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment