jdbc java_Java中使用JDBC
JDBC簡介
JDBC(Java Data Base Connectivity,java數據庫連接)是一種用于執行SQL語句的Java API,可以為多種關系數據庫提供統一訪問,它由一組用Java語言編寫的類和接口組成。
本文中中使用的數據庫
數據庫軟件:MySQL5.6
數據庫:test
表:student,其表結構如下:
+--------------+-------------+------+-----+---------+-------+
| Field??????? | Type??????? | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+-------+
| id?????????? | int(11)???? | NO?? | PRI | 0?????? |?????? |
| name???????? | varchar(20) | YES? |???? | NULL??? |?????? |
| english????? | float?????? | YES? |???? | NULL??? |?????? |
| math???????? | float?????? | YES? |???? | NULL??? |?????? |
| birthday???? | date??????? | YES? |???? | NULL??? |?????? |
| native_place | varchar(30) | YES? |???? | NULL??? |?????? |
| chinese????? | int(11)???? | YES? |???? | NULL??? |?????? |
+--------------+-------------+------+-----+---------+-------+
| student | CREATE TABLE `student` (
`id` int(11) NOT NULL DEFAULT '0',
`name` varchar(20) DEFAULT NULL,
`english` float DEFAULT NULL,
`math` float DEFAULT NULL,
`birthday` date DEFAULT NULL,
`native_place` varchar(30) DEFAULT NU
`chinese` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
JDBC的使用
建立連接
建立鏈接總共3中方式:
static Connection getConnection(String url)
static Connection getConnection(String url, Properties info)
static Connection getConnection(String url, String user, String password)
本文中將使用第3中方式。
Connection conn=null;try{
conn=DriverManager.getConnection(url_conn, user_conn, passwd_conn);
}catch(SQLException e) {
e.printStackTrace();
}
獲取statement
Statement st=null;try{
st=conn.createStatement();
}catch(SQLException e) {
e.printStackTrace();
}
執行SQL語句
1-查詢
2-插入
3-刪除
4-修改
下面為查詢的示例:
String sql_query_all_studnet="select * from student";
ResultSet res=null;try{
res=st.executeQuery(sql_query_all_studnet);
}catch(SQLException e) {
e.printStackTrace();
}try{
System.out.println("id"+"\t"+"name"+"\t"+"chinese"+"\t"+"math"+"\t"+"english");while(res.next())
{int id=res.getInt("id");
String name=res.getString("name");int chinese=res.getInt("chinese");double math=res.getDouble("math");double english=res.getDouble("english");
System.out.println(id+"\t"+name+"\t"+chinese+"\t"+math+"\t"+english);
}
}catch(SQLException e) {
e.printStackTrace();
}
結果:
id? name chinese? math??? english
1??? 潘怡茹??? 97??? 91.0??? 86.0
2??? 劉濮松??? 96??? 68.0??? 88.0
3??? 劉吉如??? 70??? 53.0??? 85.0
4??? 李巖珂??? 96??? 70.0??? 85.0
5??? 王曉博??? 46??? 79.0??? 85.0
6??? 李帥旭??? 97??? 76.0??? 79.0
7??? 李靜瑤??? 92??? 61.0??? 89.0
8??? 金紓凡??? 83??? 43.0??? 80.0
9??? 秦梓航??? 86??? 46.0??? 57.0
10??? 關穎利??? 84??? 77.0??? 80.0
關閉連接
try{
st.close();
}catch(SQLException e) {
e.printStackTrace();
}try{
conn.close();
}catch(SQLException e) {
e.printStackTrace();
}
總結
以上是生活随笔為你收集整理的jdbc java_Java中使用JDBC的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux文件和目录(linux 下目录
- 下一篇: java 招聘要求_Java程序员如何进