?? jdbc_mysql.java
字號:
/**
*2007-4-20
*下午12:21:19
*/
/**
* @author linden
*
*/
import java.sql.*;
public class JDBC_MYSQL {
public static Connection getConnection() throws SQLException,
java.lang.ClassNotFoundException {
//取得連接的url
String url = "jdbc:mysql://localhost:3306/chengji";
//加載MySQL的jdbc驅動
Class.forName("com.mysql.jdbc.Driver");
//使用能訪問MySQL數據庫的用戶名root
String userName = "root";
//使用口令
String password = "";
//打開數據庫連接
Connection con = DriverManager.getConnection(url, userName, password);
return con;
}
public static void main(String args[]) {
try {
//取得數據庫的連接
Connection con = getConnection();
//創建一個聲明,用來執行sql語句
Statement sql = con.createStatement();
//如果同名數據庫存在,刪除掉
//sql.executeUpdate("drop table if exists score");
//執行了一個sql語句生成了一個名為score的表
//sql
// .executeUpdate("create table score (name varchar(20) not null default 'name',english int not null default 60); ");
//向表中插入數據
//sql.executeUpdate("insert into score values('liyinglin',98)");
//sql.executeUpdate("insert into score values('jiangshan',79)");
//sql.executeUpdate("insert into score values('wangjiawu',100)");
//sql.executeUpdate("insert into score values('xingweiqi',89)");
//sql.executeUpdate("insert into score values('lingsheng',61)");
//執行查詢數據庫的sql語句
String query = "select * from score";
//String query = "select * from score where english>=80";
//返回一個結果集
ResultSet result = sql.executeQuery(query);
System.out.println("MYSQL中成績表數據如下:");
//使用了一個while循環打印出了score表中的所有的數據
System.out.println("--------------------");
System.out.println("姓名" + " " + "英語成績");
System.out.println("--------------------");
while (result.next()) {
String name = result.getString("name");
String mathScore = result.getString("english");
//取得數據庫中的數據
System.out.println(name + " " + mathScore);
}
//關閉聲明和連接
sql.close();
result.close();
con.close();
} catch (java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
//加載jdbc錯誤,所要用的驅動沒找到
System.err.println(e.getMessage());
//其他錯誤
} catch (SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
//顯示數據庫連接錯誤或者查詢錯誤
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -