Introduction to JDBC
JDBC (Java Data Base Connectivity,java database connection) is a Java API for executing SQL statements that provides unified access to a variety of relational databases, consisting of a set of classes and interfaces written in the Java language.
The databases that are used in this article
Database software: MySQL5.6
Database: Test
Table: Student, whose table structure is as follows:
+--------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+-------+
| ID | Int (11) | NO | PRI | 0 | |
| name | varchar (20) | YES | | NULL | |
| 中文版 | 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 (one) not NULL DEFAULT ' 0 ',
' Name ' varchar (DEFAULT NULL),
' 中文版 ' float DEFAULT NULL,
' Math ' float DEFAULT NULL,
' Birthday ' date DEFAULT NULL,
' Native_place ' varchar (+) DEFAULT NU
' Chinese ' int (one) DEFAULT NULL,
PRIMARY KEY (' id ')
) Engine=innodb DEFAULT Charset=utf8 |
Use of JDBC
Establish links in total 3 ways:
- Static Connection getconnection (String URL)
- Static Connection getconnection (String URL, Properties info)
- Static Connection getconnection (string url, string user, string password)
This article will use the 3rd method.
Connection Conn=null;
try {
Conn=drivermanager.getconnection (Url_conn, User_conn, passwd_conn);
} catch (SQLException e) {
E.printstacktrace ();
}
Statement St=null;
try {
St=conn.createstatement ();
} catch (SQLException e) {
E.printstacktrace ();
}
- Execute SQL statement
- 1-Query
- 2-Insert
- 3-Delete
- 4-Modify
The following is an example of a query:
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" + "中文版");
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 ("中文版");
System.out.println (id+ "\ t" +name+ "\ T" +chinese+ "\ T" +math+ "\ T" +english);
}
} catch (SQLException e) {
E.printstacktrace ();
}
Results:
ID name Chinese Math 中文版
1 Pan Yiju 97 91.0 86.0
2 Liu Jingsong 96 68.0 88.0
3 Liu Ji 70 53.0 85.0
4 Li Yanke 96 70.0 85.0
5 Wang Xiaobo 46 79.0 85.0
6 Li Yunxu 97 76.0 79.0
7 Li Jingyao 92 61.0 89.0
8 Gold Relief where 83 43.0 80.0
9 Qin Zi-ai 86 46.0 57.0
10 Guan Yingli 84 77.0 80.0
try {
St.close ();
} catch (SQLException e) {
E.printstacktrace ();
}
try {
Conn.close ();
} catch (SQLException e) {
E.printstacktrace ();
}
Using JDBC in Java