jdbc连接mysql

2025-10-26 13:04:00

1、加载驱动

jar程序驱动包,mysql-connector-java-5.1.21-bin.jar

jdbc连接mysql

2、java代码显示到后台的数据表格

3、package com.cc;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.Properties;

import com.mysql.jdbc.Connection;

import com.mysql.jdbc.Driver;

import com.mysql.jdbc.PreparedStatement;

public class JDBCOperation {

private static Connection getConn() {

   String driver = "com.mysql.jdbc.Driver";

   String url = "jdbc:mysql://192.168.40.6:3306/test";

   String username = "root";

   String password = "mysql2014,";

   Connection conn = null;

   try {

       Class.forName(driver); //classLoader,加载对应驱动

       conn = (Connection) DriverManager.getConnection(url, username, password);

   } catch (ClassNotFoundException e) {

       e.printStackTrace();

   } catch (SQLException e) {

       e.printStackTrace();

   }

   return conn;

}

private static Integer getAll() {

   Connection conn = getConn();

   String sql = "select * from text";

   PreparedStatement pstmt;

   try {

       pstmt = (PreparedStatement)conn.prepareStatement(sql);

       ResultSet rs = pstmt.executeQuery();

       int col = rs.getMetaData().getColumnCount();

       System.out.println("============================");

       while (rs.next()) {

           for (int i = 1; i <= col; i++) {

               System.out.print(rs.getString(i) + "\t");

               if ((i == 2) && (rs.getString(i).length() < 8)) {

                   System.out.print("\t");

               }

            }

           System.out.println("");

       }

           System.out.println("============================");

   } catch (SQLException e) {

       e.printStackTrace();

   }

   return null;

}

public static void main(String[] args) throws SQLException{

  /* Driver driver = new com.mysql.jdbc.Driver();

   String url = "jdbc:mysql://192.168.40.6:3306/test";

   Properties info=new Properties();

   info.put("user", "root");

   info.put("password", "mysql2014,");

   Connection conn= (Connection) driver.connect(url, info);

   System.out.println(conn);

   */

   JDBCOperation.getAll();

}

}

4、运行就可以在后台出现数据表格

jdbc连接mysql

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢