java,jdbc連接mysql

1.下載jdbc的驅動jar包

2.數據庫模樣:


3.上代碼:

public class JdbcTest {
	// 驅動名稱
	public static final String driverName = "com.mysql.jdbc.Driver";
	// 連接地址
	public static final String url = "jdbc:mysql://localhost:3306/libo_shopping";
	// 用戶名
	public static final String userName = "root";
	// 密碼
	public static final String password = "root";
	// 數據庫連接
	public static Connection conn = null;
	// sql語句執行對象
	public static PreparedStatement st = null;
	// 結果集對象
	public static ResultSet rs = null;
	/**
	 * 獲取數據庫連接的方法
	 * 
	 * @return
	 */
	public static void getConnection() {
		try {
			// 1.加載驅動
			Class.forName(driverName);
			// 2.獲取連接
			conn = DriverManager.getConnection(url, userName, password);
			System.out.println("成功獲取連接!");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 關閉連接的方法
	 */
	public static void close() {
		try {
			if(rs!=null){
				rs.close();
			}
			if(st!=null){
				st.close();
			}
			if(conn!=null){
				conn.close();
			}
			System.out.println("關閉成功!!");
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * main方法
	 * @param args
	 */
	public static void main(String[] args) {
		//1.獲取連接
		getConnection();
		String sql="select * from libo_shopping.y_user";
		//2.獲取sql語句執行對象
		try {
			//通過預處理防止sql注入
			st=conn.prepareStatement(sql);
			//3.獲取結果集對象
			rs=st.executeQuery();
			//4.對結果集進行處理
			System.out.println("id\t登錄名");
			while(rs.next()){
				System.out.println(rs.getInt(1)+"\t"+rs.getString(2));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			close();
		}
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章