标签:sys string https while ack package end color learn
使用mysql作为开发数据库,创建user表。创表语句如下:
create database learn; use learn; CREATE TABLE user(id INT PRIMARY KEY AUTO_INCREMENT, NAME VARCHAR(32), age INT); INSERT INTO user(NAME, age) VALUES(‘coshaho‘, 29); INSERT INTO user(NAME, age) VALUES(‘cauchy‘, 29);
一、使用Java直接连接mysql
1、添加mysql驱动
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.13</version> </dependency>
2、连接代码如下
package com.coshaho.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; /** * Java连接数据库 * @author coshaho */ public class MysqlConnector { public static void main(String[] args) { Connection con = null; Statement statement = null; ResultSet rs = null; String driver = "com.mysql.cj.jdbc.Driver"; String url = "jdbc:mysql://132.232.35.119:3306/learn"; String user = "root"; String password = "root"; try { Class.forName(driver); // 使用DriverManager获取连接 con = DriverManager.getConnection(url,user,password); // 创建statement类对象,用来执行SQL语句!! statement = con.createStatement(); String sql = "select * from user"; rs = statement.executeQuery(sql); System.out.println("name" + "\t" + "age"); int age = 0; String name = null; while(rs.next()) { // ResultSet获取返回值时,列名不区分大小写 name = rs.getString("nAme"); age = rs.getInt("age"); System.out.println(name + "\t" + age); } } catch(ClassNotFoundException e) { e.printStackTrace(); } catch(SQLException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { // 从内向外释放连接 try { if(null != rs) { rs.close(); } } catch (SQLException e) { e.printStackTrace(); } try { if(null != statement) { statement.close(); } } catch (SQLException e) { e.printStackTrace(); } try { if(null != con) { con.close(); } } catch (SQLException e) { e.printStackTrace(); } } } }
3、执行效果
标签:sys string https while ack package end color learn
原文地址:https://www.cnblogs.com/coshaho/p/10447788.html