使用MYAQL数据库用户名root密码123456创建student_sql及表student,表中包括no学号name姓名sex性别和age年龄字段使用jdbc实现成功连接mysql并查询表中age为18的记录并输出
时间: 2024-02-16 07:02:55 浏览: 29
好的,以下是使用Java JDBC连接MySQL数据库,创建表并查询数据的代码示例:
```java
import java.sql.*;
public class MySQLDemo {
public static void main(String[] args) {
// JDBC连接MySQL数据库
String url = "jdbc:mysql://localhost:3306/student_sql?useSSL=false";
String user = "root";
String password = "123456";
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 加载MySQL驱动程序
Class.forName("com.mysql.jdbc.Driver");
// 建立数据库连接
conn = DriverManager.getConnection(url, user, password);
// 创建表
stmt = conn.createStatement();
String createTable = "CREATE TABLE student (no INT(11) NOT NULL, name VARCHAR(20) NOT NULL, sex VARCHAR(4) NOT NULL, age INT(4) NOT NULL, PRIMARY KEY (no))";
stmt.executeUpdate(createTable);
// 插入数据
String insertData1 = "INSERT INTO student VALUES (1, '张三', '男', 18)";
String insertData2 = "INSERT INTO student VALUES (2, '李四', '女', 20)";
stmt.executeUpdate(insertData1);
stmt.executeUpdate(insertData2);
// 查询数据
String sql = "SELECT * FROM student WHERE age = 18";
rs = stmt.executeQuery(sql);
// 输出查询结果
while (rs.next()) {
int no = rs.getInt("no");
String name = rs.getString("name");
String sex = rs.getString("sex");
int age = rs.getInt("age");
System.out.println("no: " + no + ", name: " + name + ", sex: " + sex + ", age: " + age);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 释放资源
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
其中,`url`为MySQL数据库的连接地址,`user`和`password`为连接MySQL数据库的用户名和密码,`no`、`name`、`sex`和`age`为创建的表的字段名。
在执行查询的SQL语句时,使用`stmt.executeQuery(sql)`方法执行查询,返回的结果集通过`rs.next()`方法逐行遍历,使用`rs.getInt(columnName)`、`rs.getString(columnName)`等方法获取查询结果中的数据。
希望这个示例可以帮到你!