package com.neu;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Test0 {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
// TODO Auto-generated method stub
// Scanner input = new Scanner(System.in);
// System.out.print("请输入用户名:");
// String username = input.nextLine();
// System.out.println("请输入密码:");
// String password = input.nextLine();
Class.forName("com.mysql.jdbc.Driver");
//ctrl+2 L
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "root");
//编写sql语句
String sql = "select count(*) from stdb where sex = '女' and score>80";
//基于当前连接,得到一个执行sql语句的命令对象
// Statement statement = connection.createStatement();
PreparedStatement statement = connection.prepareStatement(sql);
// statement.setString(1, username);
// statement.setString(2, password);
//执行查询语句,返回结果集
ResultSet rs = statement.executeQuery();
//该方法读取结果集中的一条记录,如果得到下一条记录,返回true,如果没有下一条记录,返回false
while(rs.next()) {
System.out.println(rs.getInt(1));
}
rs.close();
statement.close();
//关闭连接,使用完马上关闭,释放资源
connection.close();
}
@org.junit.Test
public void testUpdate() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
//ctrl+2 L
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "root");
//编写sql语句
String sql = "update stdb set score = 100 where name like '张%' and sex='男'";
//基于当前连接,得到一个执行sql语句的命令对象
PreparedStatement statement = connection.prepareStatement(sql);
//执行sql语句,该方法一般用来执行增删改操作,返回值表示影响数据库的行数
int n = statement.executeUpdate();
if(n == 1) {
System.out.println("执行成功!");
}else {
System.out.println("执行失败!");
}
//关闭连接,使用完马上关闭,释放资源
connection.close();
}
@org.junit.Test
public void testQuery() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
//ctrl+2 L
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
//编写sql语句
String sql = "select name,sex,score from stdb where sex='女' and score>60 ";
//基于当前连接,得到一个执行sql语句的命令对象
PreparedStatement statement = connection.prepareStatement(sql);
//执行sql语句,该方法一般用来执行增删改操作,返回值表示影响数据库的行数
// int n = statement.executeUpdate(sql);
//执行查询语句,返回结果集
ResultSet rs = statement.executeQuery();
//该方法读取结果集中的一条记录,如果得到下一条记录,返回true,如果没有下一条记录,返回false
while(rs.next()) {
System.out.println(rs.getString(1));
System.out.print(rs.getString(2)+"\t");
System.out.print(rs.getInt(3)+"\t");
System.out.println();
}
rs.close();//关闭结果集
statement.close();//关闭命令
//关闭连接,使用完马上关闭,释放资源
connection.close();
}
}
12.28
最新推荐文章于 2021-08-23 08:38:19 发布