Java connects to the mysql database for content query, and java connects to the mysql database
Recently, I used the framework to do several projects. I felt a little forgotten about the underlying things. I wrote a simple JDBC connection code to familiarize myself with this, I also hope it will be helpful for new users. This is also my first article. If you don't talk much about it, go directly to 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, the premise you must import the relevant jar package to connect to the database mysql-connector-java-5.1.5-bin.jar (can be manually Baidu download ). The following is the query method:
Public List <String> getSelect (){
// SQL statement String SQL = "select * from user ";
// Obtain Connection conn = getCon (); PreparedStatement pst = null; // define a list to accept the List of content queried by the database <String> list = new ArrayList <String> (); try {pst = (PreparedStatement) conn. prepareStatement (SQL); ResultSet rs = pst.exe cuteQuery (); while (rs. next () {// Add the queried content to the list, where userName is the field name list in the database. add (rs. getString ("userName") ;}} catch (Exception e) {} return list ;}
Now we can query the data in the database. During the test, the database name is test, and the new table name is user. The field in the test contains only one userName, you can add them as needed. The following is a test of the above content:
Public static void main (String [] args) {// TestDao indicates the class name TestDao = new TestDao (); // create a new list to obtain the List returned by the query method <String> list = dao. getSelect (); // traverse the obtained list and output it 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 the TestDao class. Of course, after copying the code, you need to import the corresponding package. The Shortcut Key of the import package is Ctrl + Shift + O, if you have any shortcomings or errors, I hope you can point them out and hope you can make common progress.