Assume that the database name you want to connect to is ' MySchool ', log on with "root", password "0000", log in with the database user, and access the ' MySchool ' database.
The jar package "Mysql-connector-java-5.1.0-bin" needs to be imported before writing the code
1. Use pure Java to connect to the database to find data (for convenience, temporarily use throws to throw exceptions, omit the log).
Package CN.JBDC;
Import java.sql.Connection;
Import Java.sql.DriverManager;
Import Java.sql.ResultSet;
Import java.sql.Statement;
/**
* JDBC Program
* @author Administrator
*
*/
Public class JdbcDemo01 {
Public static void Main (string[] args) throws Exception {
//1. Loading the database driver
class.forname ("Com.mysql.jdbc.Driver");
//2. Connecting to a database
Connection connection=drivermanager.getconnection ("Jdbc:mysql://localhost:3306/myschool", "root", "0000");
//Test Connection
System.out.println (connection);
//3. Creating an object that executes an SQL statement
Statement stmt = Connection.createstatement ();
//4. Execute SQL statement get result set
ResultSet rs = stmt.executequery ("SELECT * from subject");
//5. Iterating through the result set for data
While (Rs.next ()) {
int subjectno = Rs.getint ("Subjectno");
String subjectname = rs.getstring ("Subjectname");
int classhour = Rs.getint ("Classhour");
int gradeid = Rs.getint ("Gradeid");
System.out.println (subjectno+ "\ t" +subjectname+ "\ T" +classhour+ "\ T" +gradeid);
}
//6. Releasing Resources
rs.close ();
stmt.close ();
connection.close ();
}
}
2. Use pure Java to connect the database to add and delete operations (use the Executeupdate method to modify the operation)
Package Cn.bdqn.demo;
Import java.sql.Connection;
Import Java.sql.DriverManager;
Import Java.sql.ResultSet;
Import java.sql.SQLException;
Import java.sql.Statement;
//JDBC Implementation Additions
Public class JdbcDemo3 {
Public static void Main (string[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
class.forname ("Com.mysql.jdbc.Driver");
conn = drivermanager.getconnection ("Jdbc:mysql://localhost:3306/myschool", "root", "0000");
stmt = Conn.createstatement ();
int i = stmt.executeupdate ("INSERT into ' subject ' (Subjectname,classhour,gradeid) VALUES (' History ', 101,1)");
if (i > 0) {
System.out.println ("Add success!");
}
} catch (Exception e) {
e.printstacktrace ();
} finally {
//Release Resources
if (rs! = null) {
try {
rs.close ();
} catch (SQLException e) {
e.printstacktrace ();
}
rs = null;
}
if (stmt! = null) {
try {
stmt.close ();
} catch (SQLException e) {
e.printstacktrace ();
}
stmt = null;
}
if (conn! = null) {
try {
conn.close ();
} catch (SQLException e) {
e.printstacktrace ();
}
conn = null;
}
}
}
}
How do I connect to a database using a pure Java approach?