一个简单的JDBC连接类

package ceshi;

import java.sql.*;
import java.util.*;

public class JDBCceshi {
	public static void main(String[] args){
		getConnection();
	}
	
	private static void getConnection(){
		String driverName="com.mysql.jdbc.Driver";
		String userName="mysql";
		String password="";
		String dbName = "mysql";
		try{
			String url="jdbc:mysql://localhost:3306/mysql?user="+userName+"&password="+password+"";
			Class.forName(driverName).newInstance(); 
			Connection con;
			con=DriverManager.getConnection(url);
			
			System.out.println("正确连接到mysql");
		
			Statement statement=con.createStatement();
			String sql="select * from columns_priv";
			ResultSet rs=statement.executeQuery(sql);
			ResultSetMetaData metadata=rs.getMetaData();
			int numberofColumns=metadata.getColumnCount();
			System.out.println("总共的列数是:"+numberofColumns);
			
			rs.close();
			statement.close();
			con.close();
			System.out.println("close ok!");
			
		}catch(Exception e){
			System.out.print("没有正确连接到mysql");
		}
	}
}

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