当前位置 : 主页 > 编程语言 > c++ >

本代码片用于jdbc的数据查询,有助于新手简单的了解jdbc整个工作原理和步骤

来源:互联网 收集:自由互联 发布时间:2021-06-30
JDBCTest.java package com.wang.jdbc;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.Statement;public class JDBCTest {public static void main(String[] args) {String sql = "SELECT * FROM tbl_
JDBCTest.java
package com.wang.jdbc;

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

public class JDBCTest {
	public static void main(String[] args) {
		String sql = "SELECT * FROM tbl_user";
		Connection conn = null;//当前数据库的连接
		Statement  st = null;//用于发送sql语句
		ResultSet rs = null;//代表结果集
		
		try {
			Class.forName("com.mysql.jdbc.Driver");//用来注册mysqld的jdbc的驱动程序
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jsp_db","root","123456");//获取数据库的连接
			st = conn.createStatement();//
			rs = st.executeQuery(sql);
			
			while(rs.next()){//对结果集进行遍历
				System.out.print(rs.getInt("id") + "");
				System.out.print(rs.getString("name") + "");
				System.out.print(rs.getString("password") + "");
				System.out.print(rs.getString("email") + "");
				System.out.println();
				
			}
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		finally{
			try {
				rs.close();
			} catch (Exception e2) {
			}
			try {
				st.close();
			} catch (Exception e2) {				
			}
			try {
				conn.close();
			} catch (Exception e2) {				
			}
		}
	}

}
网友评论