最簡單的JAVA連線資料庫

冰劍發表於2014-05-20

最基礎的東西都不記得了,蛋疼。

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DB {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/test";
        String user = "root";
        String passwd = "123456";
        String sql1 = "SELECT * FROM score";
        String sql2 = "INSERT INTO score VALUES(25,905,`ENGLISH`,84);";
        String sql3 = "UPDATE score SET grade=80 WHERE id=25";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection(url, user, passwd);
            System.out.println("資料庫連線成功!");
            Statement stat = con.createStatement();
            ResultSet rs = stat.executeQuery(sql1);
            while (rs.next()) {
                int id = rs.getInt("id");
                int stu_id = rs.getInt("stu_id");
                String course = rs.getString("c_name");
                int grade = rs.getInt("grade");
                System.out.println(id + " " + stu_id + " " + course + " "
                        + grade);
            }
            int i = stat.executeUpdate(sql2);
            if (i != 0) {
                System.out.println("INSERT語句執行成功!");
            }
            int j = stat.executeUpdate(sql3);
            if (j != 0) {
                System.out.println("UPDATE語句執行成功!");
            }
            if (rs != null) {
                rs.close();
                rs = null;
            }
            if (stat != null) {
                stat.close();
                stat = null;
            }
            if (con != null) {
                con.close();
                con = null;
            }
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            System.out.println("沒有找到資料庫驅動!");
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            System.out.println("連線資料庫伺服器失敗!");
        }
    }
}

相關文章