日期:2014-05-16  浏览次数:20342 次

Java连接MySQL数据库并查询结果
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.Statement;


public class Test {

	public static void main(String[] args) {
		ResultSet rs=null;
		try {
			Class.forName("com.mysql.jdbc.Driver");//驱动的类名
			Connection conn=
			(Connection) DriverManager.getConnection(
					"jdbc:mysql://127.0.0.1:3306/zhang", //服务器的IP地址和端口号,数据库的名字
					"root",//用户名
					"128928818"//密码
					);
			Statement stmt=(Statement) conn.createStatement();
			rs=stmt.executeQuery("select * from student");
			while(rs.next())
			{
				System.out.println(rs.getInt(1));
				System.out.println(rs.getString(2));
				System.out.println(rs.getString(3));
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally
		{
			if(rs!=null)
			{
				try {
					rs.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

}

MySQL的驱动。下载