java gui 连接mysql数据库
生活随笔
收集整理的這篇文章主要介紹了
java gui 连接mysql数据库
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?
?
package com.wt010.db;import java.sql.*;import javax.swing.JFrame; import javax.swing.JTextArea;public class MySQLUtil extends JFrame {// JDBC 驅動名及數據庫 URLstatic final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost:3306/w_w84_xinxy";// 數據庫的用戶名與密碼,需要根據自己的設置static final String USER = "root";static final String PASS = "kwlloveh";private JTextArea ta;public MySQLUtil() {// TODO Auto-generated constructor stub fm();connect();}public void fm() {this.setTitle("MySQL");this.setSize(300, 300);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setLocationRelativeTo(null);ta=new JTextArea(30,50);this.add(ta);}public void connect() {Connection conn = null;Statement stmt = null;try{// 注冊 JDBC 驅動Class.forName("com.mysql.jdbc.Driver");// 打開鏈接ta.append("連接數據庫...\r\n");conn = DriverManager.getConnection(DB_URL,USER,PASS);// 執行查詢ta.append(" 實例化Statement對...\r\n");stmt = conn.createStatement();String sql;sql = "SELECT * FROM admin_tb";ResultSet rs = stmt.executeQuery(sql);// 展開結果集數據庫while(rs.next()){// 通過字段檢索int id = rs.getInt("id");String name = rs.getString("adminname");// 輸出數據ta.append("ID: " + id+"\r\n");ta.append(", 管理員: " + name+"\r\n"); }// 完成后關閉 rs.close();stmt.close();conn.close();}catch(SQLException se){// 處理 JDBC 錯誤 se.printStackTrace();}catch(Exception e){// 處理 Class.forName 錯誤 e.printStackTrace();}finally{// 關閉資源try{if(stmt!=null) stmt.close();}catch(SQLException se2){}// 什么都不做try{if(conn!=null) conn.close();}catch(SQLException se){se.printStackTrace();}}System.out.println("Goodbye!");}public static void main(String[] args) {MySQLUtil mysql=new MySQLUtil();mysql.setVisible(true);} }?
轉載于:https://www.cnblogs.com/phpdo100/p/8400184.html
總結
以上是生活随笔為你收集整理的java gui 连接mysql数据库的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JAVA基础学习之路(三)类定义及构造方
- 下一篇: python 全栈开发,Day63(子查