Detailed explanation of JDBC database connection code and steps in java
JDBC connection database
•Create a program to connect to the database with JDBC, including 7 steps:
1. Load the JDBC driver:
Before connecting to the database, you must first load the driver of the database you want to connect to. To the JVM (Java Virtual Machine), this is achieved through the static method forName(String className) of the java.lang.Class class.
For example:
##
try{ //加载MySql的驱动类 Class.forName("com.mysql.jdbc.Driver") ; }catch(ClassNotFoundException e){ System.out.println("找不到驱动程序类 ,加载驱动失败!"); e.printStackTrace() ; }
2. Provide the URL of the JDBC connection
•Writing form: Protocol: Subprotocol: Data source identifier
jdbc:mysql: //localhost:3306/test?useUnicode=true&characterEncoding=gbk ;
3. Create a database connection
•Use DriverManager's getConnectin(String url, String username, String password) method to pass in the path to the specified database to be connected, the username of the database and the password
//连接MySql数据库,用户名和密码都是root String url = "jdbc:mysql://localhost:3306/test" ; String username = "root" ; String password = "root" ; try{ Connection con = DriverManager.getConnection(url , username , password ) ; }catch(SQLException se){ System.out.println("数据库连接失败!"); se.printStackTrace() ; }
•To execute a SQL statement, you must obtain a java.sql.Statement instance. Statement instances are divided into the following 3 types:
1. Execute static SQL statements. Usually implemented through Statement instances.
3. Execute the database stored procedure. Usually implemented through a CallableStatement instance.
Specific implementation method:
, returns a result set (ResultSet) object.
2. int executeUpdate(String sqlString): used to execute INSERT, UPDATE or DELETE statements and SQL DDL statements, such as: CREATE TABLE and DROP TABLE, etc.
Specific implementation code:
Statement stmt = con.createStatement() ; PreparedStatement pstmt = con.prepareStatement(sql) ; CallableStatement cstmt = con.prepareCall("{CALL demoSp(? , ?)}") ;
## 6. Processing results
Two situations:
1. Executing an update returns the number of records affected by this operation.
2. The result returned by executing the query is a ResultSet object.
• ResultSet contains all rows that match the conditions in the SQL statement, and it provides access to the data in these rows through a set of get methods.
ResultSet rs = stmt.executeQuery("SELECT * FROM ...") ; int rows = stmt.executeUpdate("INSERT INTO ...") ; boolean flag = stmt.execute(String sql) ;
7、关闭JDBC对象
操作完成以后要把所有使用的JDBC对象全都关闭,以释放JDBC资源,关闭顺序和声 明顺序相反:
1、关闭记录集
2、关闭声明
3、关闭连接对象
if(rs != null){ // 关闭记录集 try{ rs.close() ; }catch(SQLException e){ e.printStackTrace() ; } } if(stmt != null){ // 关闭声明 try{ stmt.close() ; }catch(SQLException e){ e.printStackTrace() ; } } if(conn != null){ // 关闭连接对象 try{ conn.close() ; }catch(SQLException e){ e.printStackTrace() ; } }
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
更多java 中JDBC连接数据库和步骤详解及实例相关文章请关注PHP中文网!