JDBC Java连接MySQL

   MySQL数据库驱动下载:http://download.csdn.net/detail/u012005313/8627705


package com;

import java.sql.*;
/**
 * 
 * @author zhujian
 * 数据库连接
 *
 */
public class DBConn {
	private static String CLASSFORNAME="com.mysql.jdbc.Driver";
	private static String URL="jdbc:mysql://localhost:3306/testDB";//testDB为数据库名
	private static String USERNAME="root";
	private static String PASSWORD="zhujian";//密码
	
	private static Connection conn;
	private static Statement stmt;
	private static ResultSet rs;
	
	public static void main(String[] args) {
		//装载MySQL JDBC驱动程序
		try {
			Class.forName(CLASSFORNAME);
		} catch (ClassNotFoundException e){
			System.out.println("找不到驱动程序类,加载驱动失败");
			e.printStackTrace();
		}
		try {
			//创建与数据源的连接
			conn=DriverManager.getConnection(URL, USERNAME, PASSWORD);
			//创建一个statement
			stmt=conn.createStatement();
			//执行SQL语句
			String sql="select * from student";
			//得到记录集
			rs=stmt.executeQuery(sql);
			//输出
			while (rs.next())
			{
				//列是从左到右编号的,并且从列1开始
				System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));//下标从1开始
			}
		} catch (Exception e){
			e.printStackTrace();
		} finally {
			try {
			if (rs != null)//关闭记录集
				rs.close();
			if (stmt != null)//关闭声明
				stmt.close();
			if (conn != null)//关闭连接
				conn.close();
			} catch (SQLException e)
			{
				e.printStackTrace();
			}
		}
	}
}











你可能感兴趣的:(java,mysql,jdbc)