Java Web Connection MySQL

Source: Internet
Author: User

1. Create a database

1 CREATE database jdbc;

2. Create a data table

1 int (ten) primary key auto_increment, name varchar (null, age varchar (null , Address varchar (null);

3. Adding data through INSERT statements

1 INSERT INTO STU10 values (1,' yards-slave ','a ', ' Jiaxing, Zhejiang ');

4. Create a Connection database class

1 Package Com.tu.jdbc;2 3 import java.sql.Connection;4 import Java.sql.DriverManager;5 import java.sql.SQLException;6 7  Public classJdbc_con {8      PublicConnection getconnection () {9         Try {Ten             //Load Database driver OneClass.forName ("Com.mysql.jdbc.Driver"); A             //connecting to a database -             returnDrivermanager.getconnection ("Jdbc:mysql://localhost:3306/jdbc","Root","123"); -}Catch(Exception e) { the             //TODO auto-generated Catch block - e.printstacktrace (); -         } -         return NULL; +     } -      +      Public voidcloseconection (Connection con) { A         if(con!=NULL){ at             Try { - con.close (); -}Catch(SQLException e) { -                 //TODO auto-generated Catch block - e.printstacktrace (); -             } in         } -     } to}

5. Create a test class

1 Package Com.tu.jdbc;2 3 import java.sql.Connection;4 import Java.sql.ResultSet;5 import java.sql.SQLException;6 import java.sql.Statement;7 8  Public classTest {9 Ten      Public Static voidMain (string[] args) { OneTest ts =NewTest (); A ts.list (); -  -     } the  -      Public voidlist () { -Jdbc_con JC =NewJdbc_con (); -Connection JDBC =jc.getconnection (); +String sql ="Select Id,name from Stu10"; -         Try { +Statement SM =jdbc.createstatement (); AResultSet rs =sm.executequery (SQL); at              while(Rs.next ()) { -                 intid = rs.getint (1); -String name = Rs.getstring (2); -System. out. println (ID +name); -             } -}Catch(SQLException e) { in             //TODO auto-generated Catch block - e.printstacktrace (); to         } +  -     } the}

Java Web Connection MySQL

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.