Java连接MySQL例

package com.zy.test;

import java.sql.*;

public class TestMysql {

	
	
	public static void main(String[] args) {
		
		
		String driver = "com.mysql.jdbc.Driver";
                //?useUnicode=true&characterEncoding=UTF-8防止数据库乱码
               String url = "jdbc:mysql://localhost:3306/zybd1?useUnicode=true&characterEncoding=UTF-8";
		String user = "root";
		String pwd = "123456";
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(url,user,pwd);
			ps = conn.prepareStatement("select * from student");
			rs = ps.executeQuery();
			while(rs.next()){
				System.out.println(rs.getInt(1) + "\t" + rs.getString(2) + "\t" + rs.getFloat("math"));
			}
		} 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();
				}
				rs = null;
			}
			
			if (ps != null){
				try {
					ps.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				ps = null;
			}
			if (conn != null){
				try {
					conn.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				conn = null;
			}
		}
	}
	
	
}

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