Java MySQL database and query for content
Recently used the framework to do a few projects, feeling that the bottom of the things a bit forgotten, write a JDBC Simple connection code to familiarize yourself with the review, but also hope that the new contact to help the novice. This is also my first essay, nonsense not much to say, directly on the code:
Public Connection Getcon () {
//database connection name
String username= "root";
Database connection password
String password= "";
String driver= "Com.mysql.jdbc.Driver";
Where test is the database name
String 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 ();
}
return conn;
}
Through the above code can be directly connected to the database, of course, you must import the database connected to the relevant jar package Mysql-connector-java-5.1.5-bin.jar (can be downloaded by oneself Baidu). Then the following are the methods of the query:
Public list<string> Getselect () {
//SQL statement
String sql = "SELECT * from user";
Gets to the connection
Connection conn = Getcon ();
PreparedStatement PST = NULL;
Define a list to accept the contents of a database query
list<string> List = new arraylist<string> ();
try {
PST = (preparedstatement) conn.preparestatement (SQL);
ResultSet rs = Pst.executequery ();
while (Rs.next ()) {
//Add the contents of the query to the list, where UserName is the name of the field in the database
List.add (rs.getstring ("UserName"));
}
catch (Exception e) {
} return
list;
}
At this point can be in the database query data, I tested the database name for test, the new table name is user, inside the field only a 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 Testdao ();
A new list gets the collection returned in the Query method
list<string> List = Dao.getselect ();
The resulting list is traversed for output to the console for
(int i = 0; i < list.size (); i++) {
System.out.println (List.get (i));
}
}
For 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 key for Ctrl+shift+o, if there is any shortage or wrong place hope everyone points out, look forward to common progress
Thank you for reading, I hope to help you, thank you for your support for this site!