?? databasetest.java
字號(hào):
/*
* 創(chuàng)建日期 2005-8-10
*
* TODO 要更改此生成的文件的模板,請(qǐng)轉(zhuǎn)至
* 窗口 - 首選項(xiàng) - Java - 代碼樣式 - 代碼模板
*/
package com.example.eclipse.java1;
import java.sql.*;
/**
* @author wufenghanren
*
* TODO 要更改此生成的類型注釋的模板,請(qǐng)轉(zhuǎn)至 窗口 - 首選項(xiàng) - Java - 代碼樣式 - 代碼模板
*/
public class DataBaseTest {
public static Connection getConnection() throws SQLException,
java.lang.ClassNotFoundException {
//取得連接的url
String url = "jdbc:mysql://localhost:3306/studentinfo";
//加載MySQL的jdbc驅(qū)動(dòng)
Class.forName("com.mysql.jdbc.Driver");
//使用能訪問(wèn)MySQL數(shù)據(jù)庫(kù)的用戶名root
String userName = "root";
//使用口令
String password = "admin";
//打開(kāi)數(shù)據(jù)庫(kù)連接
Connection con = DriverManager.getConnection(url, userName, password);
return con;
}
public static void main(String args[]) {
try {
//取得數(shù)據(jù)庫(kù)的連接
Connection con = getConnection();
//創(chuàng)建一個(gè)聲明,用來(lái)執(zhí)行sql語(yǔ)句
Statement sql = con.createStatement();
//如果同名數(shù)據(jù)庫(kù)存在,刪除掉
sql.executeUpdate("drop table if exists student");
//執(zhí)行了一個(gè)sql語(yǔ)句生成了一個(gè)名為student的表
sql
.executeUpdate("create table student (id int not null auto_increment,name varchar(20) not null default 'name',math int not null default 60,primary key (id)); ");
//向表中插入數(shù)據(jù)
sql.executeUpdate("insert student values(1,'liyinglin',98)");
sql.executeUpdate("insert student values(2,'jiangshan',79)");
sql.executeUpdate("insert student values(3,'wangjiawu',100)");
sql.executeUpdate("insert student values(4,'xingweiqi',89)");
sql.executeUpdate("insert student values(5,'lingsheng',61)");
//執(zhí)行查詢數(shù)據(jù)庫(kù)的sql語(yǔ)句
String query = "select * from student";
//返回一個(gè)結(jié)果集
ResultSet result = sql.executeQuery(query);
System.out.println("Student表中的數(shù)據(jù)如下:");
//使用了一個(gè)while循環(huán)打印出了student表中的所有的數(shù)據(jù)
System.out.println("----------------------------------");
System.out.println("學(xué)號(hào) " + " " + "姓名" + " " + "數(shù)學(xué)成績(jī)");
System.out.println("----------------------------------");
while (result.next()) {
int number = result.getInt("id");
String name = result.getString("name");
String mathScore = result.getString("math");
//取得數(shù)據(jù)庫(kù)中的數(shù)據(jù)
System.out.println(" " + number + " " + name + " "
+ mathScore);
}
//關(guān)閉聲明和連接
sql.close();
con.close();
} catch (java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
//加載jdbc錯(cuò)誤,所要用的驅(qū)動(dòng)沒(méi)找到
System.err.println(e.getMessage());
//其他錯(cuò)誤
} catch (SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
//顯示數(shù)據(jù)庫(kù)連接錯(cuò)誤或者查詢錯(cuò)誤
}
}
}
?? 快捷鍵說(shuō)明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -