JDBC连接数据库代码 (一) -- 一个简单的获取数据库表单


一个简单的获取数据库表单代码


连接步骤:

1.加载数据库驱动(jar包)

2.获得数据库连接

3.创建SQL语句

4.执行查询

5.遍历结果集

5.关闭数据库连



具体实例:

package com.nenu.www;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

import java.sql.Statement;

public class JdbcConn {
	
	public static void main(String[] args) {
		
		try {
			Class.forName("com.mysql.jdbc.Driver");//导入驱动(jar包)
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		
		Connection conn = null; 
		try {
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");//建立连接
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		String sql = "select name,email,dob from student";//建立SQL语句
		
		try {
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(sql);
			//cursor
			while(rs.next()){
				String name = rs.getString(1);
				String email = rs.getString(2);
				String dob = rs.getString(3);
				System.out.println(name+" , "+email+" , "+dob);
				
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			if(conn!=null)
				try {
					conn.close();//关闭连接
				} catch (SQLException e) {
					e.printStackTrace();
				}	
		}
		
		
	}
}

(同样打开MySQL命令行也可打开相应数据库内容)如下:
Enter password: ****
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 9
Server version: 5.6.21-log MySQL Community Server (GPL)

Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> use localhost database
Database changed
mysql> select * from test
    -> ;
ERROR 1146 (42S02): Table 'localhost.test' doesn't exist
mysql> use test database
Database changed
mysql> select * from student;
+---------+--------+-----------+------------+
| stud_id | name   | email     | dob        |
+---------+--------+-----------+------------+
|       1 | 哈哈   | 198493290 | 2017-12-13 |
|       2 | 李zz   | 343908409 | 2017-12-13 |
|       3 | zzzz   | 398479284 | 2017-12-13 |
+---------+--------+-----------+------------+
3 rows in set (0.00 sec)

mysql>

 

你可能感兴趣的:(jdbc,MySQL,数据库连接)