I remember sophomore time, we went to the Java class, when the teacher said that JDBC this thing, nor how to learn, until now, I do not until the JDBC is what thing, I know this thing can extract data from the database, then what is JDBC?
JDBC is the abbreviation of Java Database connectivity, meaning that the connection of Java databases, do not need to explain more, I feel!
So how do we make a connection like this? Once used once will find, in fact very simple, remember a few steps, there is the need to import the necessary driver package on it, here are a few important steps:
The first step is that you must import the necessary database driver packages in your project environment, I am here to use Oracle 11g database as an example of the demo, I have to import into the project and add to the classpath of the Web project, Oracle, The Class12.jar package is now ready to be imported.
The second step is to start writing the code and instantiate your driver package:
Class.forName ("Oracle.jdbc.driver.OracleDriver");//Other databases just modify the string parameter values.
Step three: Create the connection, here we need to use the DriverManager drive tube class
Connection conn = Drivermanager.getconnection ("Jdbc:oracle:thin: @localhost: 1521:cgzs", "System", "hj123"); Just beginning to learn, the teachers are talking about this operation class, in fact, now very few people use this, in detail, I have another blog inside there will be introduced
Fourth step: The driver instantiation, also get to the connection, then start querying the database bar, we need a database SQL state object, we also need a query result set receive object, respectively, statement object and ResultSet object
Statement s = conn.createstatement (); ResultSet rs = Null;rs = S.executequery ("SELECT ID from A"), while (Rs.next ()) {System.out.println (rs.getstring ("id"));}
The last step: don't forget that the statement object that we used earlier, the ResultSet object and the connection object need to close the connection, or else it will be finished.
Well, that's all, it's very simple, I wrote a complete demo!
public class Demo {/** * @param args * @throws SQLException * @throws classnotfoundexception */public static void Main (STR Ing[] args) throws Sqlexception,classnotfoundexception {//TODO auto-generated method stub//Instantiate drive Class.forName (" Oracle.jdbc.driver.OracleDriver ");//Establish connection Connection conn = Drivermanager.getconnection (" jdbc:oracle:thin:@ Localhost:1521:cgzs "," System "," hj123 ");//Statement object used to interact with the database statement s = conn.createstatement ();// Perform a query operation resultset rs = s.executequery ("SELECT * from V_cancle"), while (Rs.next ()) {//Print query Results System.out.println ( Rs.getstring ("WWID"));} Close connection, critical conn.close (); S.close (); Rs.close ();}}