Recently using the framework to do a few projects, feel that the bottom of things a bit forgotten, write a simple JDBC connection code to familiarize yourself with the review, but also hope that the new contact Novice can be helpful. This is also my first essay, nonsense not much to say, directly on the code:
PublicConnection Getcon () {//Database Connection NameString username= "Root"; //Database connection PasswordString password= ""; String Driver= "Com.mysql.jdbc.Driver"; //where test is the database nameString url= "Jdbc:mysql://localhost:3306/test"; Connection Conn=NULL; Try{class.forname (driver); Conn=(Connection) drivermanager.getconnection (Url,username,password); }Catch(Exception e) {e.printstacktrace (); } returnConn; }
Through the above code can be directly connected to the database, of course, you must import the connection database of the relevant JAR package Mysql-connector-java-5.1.5-bin.jar (Baidu can be downloaded by itself). Then the following is the method of the query:
PublicList<string> Getselect () {
//SQL statementsString sql = "SELECT * from user";
//Get to ConnectionConnection conn =Getcon (); PreparedStatement PST=NULL; //define a list to accept the contents of a database querylist<string> list =NewArraylist<string>(); Try{PST=(PreparedStatement) conn.preparestatement (SQL); ResultSet RS=Pst.executequery (); while(Rs.next ()) {//Add the queried content to the list, where username is the field name in the databaseList.add (rs.getstring ("UserName")); } } Catch(Exception e) {}returnlist; }
At this point in the database can query out the data, I test with the database name is test, the name of the new table is user, the field has only one username, we can add according to their own needs, the following is the test of the above content:
public static void main (string[] args) { // where Testdao is the class name Testdao DAO = new T Estdao (); // Create a new List to get the collection returned in the Query method list< string> list = Dao.getselect (); // traverse the resulting list output to the console for (int i = 0; i < list.size (); I++
For the sake of convenience, the above three methods are written in Testdao this class, of course, after copying the code needs to import the corresponding package, import package shortcut keys for Ctrl+shift+o, if there is any shortage or wrong place want everyone to point out, look forward to common progress
Java connects to MySQL database and queries content