java连接mysql的一般操作流程

java连接mysql
package com.test;

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

public class TestJDBC {
	
	public static void main(String[] args) {
		
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		try{
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncode=utf-8","root","admin");
			stmt = conn.createStatement();
			rs = stmt.executeQuery("SELECT * FROM students");
			while(rs.next()){
				System.out.println(rs.getString("name"));
				System.out.println(rs.getString("sex"));
			}
		}catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(rs != null){
				try{
					rs.close();
				}catch (Exception e) {
					e.printStackTrace();
				}
			}
			if(stmt != null){
				try{
					stmt.close();
				}catch (Exception e) {
					e.printStackTrace();
				}
			}
			if(conn != null){
				try{
					conn.close();
				}catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
}

你可能感兴趣的:(mysql)