What is JDBC
JDBC is all called: Java Data Base Connectivity, which is the Java API that can execute SQL statements
Why are we using JDBC?
- There are a lot of databases on the market, originally we need to learn from different databases of different api,sun companies in order to simplify this operation, defined the JDBC API "interface"
- Sun only provided the JDBC API "interface", which the database vendor was responsible for.
- For us, the Operational database is on the JDBC API "interface" , using a different database, as long as the database vendor provides a database driver can be
- This greatly simplifies our learning costs.
Simple Operation JDBC
Steps:
- Importing MySQL or Oracle driver packages
- Loading the database driver
- Gets the connection to the database
- Gets the object that can execute the SQL statement
- Execute SQL statement
- Close connection
Connection Connection =NULL; Statement Statement =NULL; ResultSet ResultSet =NULL;Try{/** There are two ways to load drivers ** 1: Will cause the driver to register two times, over-reliance on the MySQL API, out of the MySQL development package, the program will not compile* 2: The driver is only loaded once, it does not need to rely on the specific drive, the flexibility is high ** We generally use the second way * */ //1. //drivermanager.registerdriver (New Com.mysql.jdbc.Driver ()); //2.Class.forname("Com.mysql.jdbc.Driver");//Gets the object connected to the database-connetcionConnection = DriverManager.getconnection("Jdbc:mysql://localhost:3306/zhongfucheng","Root","Root");//Gets the statement object that executes the SQL statementstatement = connection.createstatement();//Execute SQL statement, get result setResultSet = statement.ExecuteQuery("SELECT * from users");//traverse the result set to get the data while(ResultSet.Next()) {System. out.println(ResultSet.getString(1)); System. out.println(ResultSet.getString(2)); } }Catch(SQLException e) {e.Printstacktrace(); }Catch(ClassNotFoundException e) {e.Printstacktrace(); }finally{/** Close resource, after call is closed first ** Before closing, to determine if an object exists * */ if(ResultSet! =NULL) {Try{ResultSet.Close(); }Catch(SQLException e) {e.Printstacktrace(); } }if(Statement! =NULL) {Try{statement.Close(); }Catch(SQLException e) {e.Printstacktrace(); } }if(Connection! =NULL) {Try{connection.Close(); }Catch(SQLException e) {e.Printstacktrace(); } } }
Above we have simply used JDBC to query the database data, and then we go to the above code to understand the object used
Connection object
Client-to-database interaction is done through connection.
Common methods:
//创建向数据库发送sql的statement对象。createcreateStatement()//创建向数据库发送预编译sql的PrepareSatement对象。prepareStatement//创建执行存储过程的callableStatement对象prepareCall(sql)//设置事务自动提交setAutoCommit(boolean autoCommit)//提交事务commit()//回滚事务rollback()
Statement Object
The statement object is used to send SQL statements to the database , and additions and deletions to the database can be sent through this object to complete the SQL statement.
Common methods for statement objects:
//查询executeQuery(String sql)//增删改executeUpdate(String sql)//任意sql语句都可以,但是目标不明确,很少用execute(String sql)//把多条的sql语句放进同一个批处理中addBatch(String sql)//向数据库发送一批sql语句执行executeBatch()
ResultSet Object
The ResultSet object represents the execution result of the SQL statement , and when the statement object executes ExecuteQuery (), a ResultSet object is returned
The ResultSet object maintains a data row cursor "Simply understood as a pointer" and calls the Resultset.next () method, allowing the cursor to point to a specific row of data to fetch the row's data
Common methods:
//获取任意类型的数据getObject(String columnName)//获取指定类型的数据【各种类型,查看API】getString(String columnName)//对结果集进行滚动查看的方法next()Previous()absolute(int row)beforeFirst()afterLast()
Write a simple tool class
Through the above understanding, we have been able to use the JDBC database data to be modified and checked, we found that both add and delete changes need to connect to the database, close the resources, so we will connect the database, release the resources of the operation extracted to a tool class
/** The Driver,url,username,password connected to the database can be configured with a configuration file for added flexibility* When we need to switch the database, only need to change the above information in the configuration file * * */ Private StaticString Driver =NULL;Private StaticString URL =NULL;Private StaticString username =NULL;Private StaticString Password =NULL;Static{Try{//Get the read stream of the configuration fileInputStream InputStream = Utilsdemo.class.getClassLoader().getResourceAsStream("Db.properties"); Properties Properties =NewProperties (); Properties.Load(InputStream);//Get information about the configuration fileDriver = properties.GetProperty("Driver"); url = properties.GetProperty("url"); Username = properties.GetProperty("username"); Password = properties.GetProperty("Password");//Load driver classClass.forname(driver); }Catch(IOException e) {e.Printstacktrace(); }Catch(ClassNotFoundException e) {e.Printstacktrace(); } } Public StaticConnectiongetconnection()throwsSQLException {returnDriverManager.getconnection(Url,username,password); } Public Static void Release(Connection Connection, Statement Statement, ResultSet ResultSet) {if(ResultSet! =NULL) {Try{ResultSet.Close(); }Catch(SQLException e) {e.Printstacktrace(); } }if(Statement! =NULL) {Try{statement.Close(); }Catch(SQLException e) {e.Printstacktrace(); } }if(Connection! =NULL) {Try{connection.Close(); }Catch(SQLException e) {e.Printstacktrace(); } } }
If the article is wrong, welcome to correct, we communicate with each other. Students who are accustomed to reading technical articles can pay attention to the public number: Java3y
JDBC "Introducing JDBC, using JDBC to connect to a database, a simple tool class"