1. First import the jar package
The first one for MySQL driver package
The second is an Oracle driver package
2. The following steps are shown in the Code
ImportJava.sql.Connection;ImportJava.sql.DriverManager;ImportJava.sql.PreparedStatement;ImportJava.sql.ResultSet;/** * JDBC Programming * @author ASDC * * * * Public class testjdbc { Public Static void Main(string[] args) {//Using a database connectionConnection Connection =NULL;//Use precompiled statement to improve database performance with precompiled statementPreparedStatement PreparedStatement =NULL;//Result setResultSet ResultSet =NULL;Try{//1. Loading a database driver packageClass.forName ("Com.mysql.jdbc.Driver");//2. Getting a database connection through drive managementConnection = Drivermanager.getconnection ("");//3. Defining SQL StatementsString sql ="SELECT * from Users where id =?";//4. Getting preprocessing statement, setting parametersPreparedStatement = connection.preparestatement (sql); Preparedstatement.setstring (1,"1111");//5. Issuing SQL execution queries to the database to isolate the result setResultSet = Preparedstatement.executequery ();//6. Traversing a query result set while(Resultset.next ()) {System.out.println (resultset.getstring ("id")+","+resultset.getstring ("UserName")); } }Catch(Exception e) {//TODO auto-generated catch blockE.printstacktrace (); }finally{//Release resources from bottom up if(ResultSet! =NULL){Try{Resultset.close (); }Catch(Exception E2) {//Todo:handle exception} }if(PreparedStatement! =NULL){Try{Preparedstatement.close (); }Catch(Exception E2) {//Todo:handle exception} }if(Connection! =NULL){Try{Connection.close (); }Catch(Exception E2) {//Todo:handle exception} } } }}
3. Summary of Issues
①. When the database connection is created, it is turned off and the database is frequently operated. Affect database performance
Solution: Use a database connection pool
② hard-coded into Java code when using SQL queries, and if you need to modify the SQL statement, you need to recompile the Java code, which is not conducive to system maintenance
Solution: Configure SQL statements into XML without recompiling the Java code even if the SQL is changed
③ set parameters to PreparedStatement, hard-coded into Java code when setting parameters on placeholder position, not conducive to system maintenance
Solution: Configure into XML, without recompiling the Java code, even if SQL is changed
④ hard-coded when querying from the result set such as: Resultset.getstring ("id")
Solution: Query completion is mapped directly into an object
1. The original ecological JDBC programming detailed and the problem summary