(Detailed) connecting to MySQL database using JDBC in JAVA (3)-code section, jdbcmysql

Source: Internet
Author: User

(Detailed) connecting to MySQL database using JDBC in JAVA (3)-code section, jdbcmysql

You are welcome to reprint it in any form, but be sure to indicate the source.

1. Project Establishment

: Create a Java Project, Package, and Class

2. Database Connection
1 ********************/ 2 public static Connection conn () {3 Connection conn = null; 4 5 String driver = "com. mysql. jdbc. driver "; 6 String url =" jdbc: mysql: // localhost: 3306/demo? CharacterEncoding = UTF-8 "; 7 String username =" root "; 8 String pw =" 111111 "; 9 10 try {11 Class. forName (driver); // load the MySql driver Class 12 System. out. println ("driver loaded successfully !!!! "); 13 conn = (Connection) DriverManager. getConnection (url, username, pw); // create a database connection 14} catch (Exception e) {15 // TODO: handle exception16 System. out. println ("The driver class cannot be found. Failed to load the driver! "); 17 e. printStackTrace (); 18} 19 return conn; 20}
3. Database Operations
1. * public void showTable () {3 Connection conn = conn (); 4 PreparedStatement pstmt = null; // create a Statement 5 ResultSet rs = null; // create result set 6 String SQL = "select * from user"; // SQL statement 7 try {8 pstmt = (PreparedStatement) conn. prepareStatement (SQL); 9 rs = pstmt.exe cuteQuery (); // Execute SQL statement 10 while (rs. next () {// processing result 11 System. out. println (rs. getString (1) + "\ t" + rs. getString (2); 12} 13 rs. close (); // close the record set 14 pstmt. close (); // close the Declaration 15 conn. close (); // close the connection object 16} catch (SQLException e) {17 e. getStackTrace (); 18} 19}
4. Main Function content
1 public static void main(String[] args) {2         // TODO Auto-generated method stub3         Connsql sql = new Connsql();4         sql.showTable();5     }

Series of articles

(Detailed) connecting to the MySQL database using JDBC in JAVA (2)-MySQL ors

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.