jdbc连接mysql

作者:神奇的周 | 创建时间: 2023-06-19
JDBC(Java Data Base Connectivity,java数据库连接)是一种用于执行SQL语句的Java API,可以为多种关系数据库提供统一访问,它由一组用Java语言编写的类和接口组成。JDBC提供了一种基准,据此可以构...
jdbc连接mysql

操作方法

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

java代码显示到后台的数据表格 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(); } }

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

点击展开全文

更多推荐