怎样使用Java连接Mysql数据

怎样使用Java连接Mysql数据库

    

    废话不多说上代码

    

package conM;

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

public class Cnn {
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		java.sql.Connection con = null;                        
		String driver ="com.mysql.jdbc.Driver";            
		String url="jdbc:mysql://localhost:3306/ed";       
		String user="root";
		String password="1234";
		
		try {
			Class.forName(driver);
			con=DriverManager.getConnection(url, user, password);
			if(!con.isClosed())
				System.out.println("Successded connectingtothe Database");
			Statement statement = con.createStatement();
			String sql = "select * from emp";
			ResultSet rs=statement.executeQuery(sql);
			while(rs.next()) {
				String rowT="" ;
				for(int i=1;i<=rs.getMetaData().getColumnCount();i++) {              
					rowT+=rs.getString(rs.getMetaData().getColumnName(i))+" ";
				}
				System.out.println(rowT);
			}
			rs.close();                                               
			con.close();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			System.out.println("Sorry,can`t find the Driver!");  
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			  System.out.println("数据库数据成功获取!!");
		}
		
		
		
		
		
		
	}

}

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页