jdbc连接mysql
JDBC(Java Data Base Connectivity,java数据库连接)是一种用于执行SQL语句的Java API,可以为多种关系数据库提供统一访问,它由一组用Java语言编写的类和接口组成。JDBC提供了一种基准,据此可以构建更高级的工具和接口,使数据库开发人员能够编写数据库应用程序。
如果要使用数据库就要添加数据库的驱动,不同的数据库有不用的驱动,这里就不一一说明,添加jar程序驱动包的方法就不在这里解释,
操作方法
- 01
加载驱动 jar程序驱动包,mysql-connector-java-5.1.21-bin.jar
- 02
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(); } }
- 03
运行就可以在后台出现数据表格