(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