标题: 如何调用数据库,完成下列需求,求解答 [打印本页] 作者: 18211001681 时间: 2016-8-10 00:56 标题: 如何调用数据库,完成下列需求,求解答 3.一个数据库stu,用户名为admin 密码为123456 已存在一个表中有五个学生的信息,姓名,性别,年龄,分数.
id name sex score
1 李少荣 女 80
2 邵凯 男 75
3 周强 男 95
4 王晓婷 女 55
5 张秀花 女 68
6 顾会 女 50
7 赵天一 男 32
(1)查询女性,成绩80以上
(2)将姓张的男同学的的成绩改为100
(3)查询年龄大于20的女性,显示姓名,性别,年龄作者: 水月灬清影 时间: 2016-8-10 20:08
今天突击的mySQL,我写下,你试下:
(1)条件查询:
SELECT * FROM stu WHERE sex='女' AND score>=80;
(2)修改数据(含模糊查询):
UPDATE stu SET score=100 WHERE sex='男' AND name like '张%';
(3)条件查询(显示部分列):
SELECT name,sex,age FROM stu WHERE sex='女' AND age>20;
public class demo1
{
static String name = "com.mysql.jdbc.Driver";
static String user = "root";
static String password = "123";
static String url = "jdbc:mysql://127.0.0.1:3306/stu";
public static void main(String[] args) throws ClassNotFoundException, SQLException
{
Statement stat = con();
method(stat);
method1(stat);
method2(stat);
}
public static Statement con() throws SQLException, ClassNotFoundException
{
Class.forName(name);
Connection con = DriverManager.getConnection(url, user, password);
Statement stat = con.createStatement();
return stat;
}
public static void method(Statement stat) throws SQLException
{
String s = "insert into studb (i_name,i_sex,score) values ('李少荣','女',80)," +
"('邵凯','男',75),('周强','男',95),('王晓婷','女',55)," +
"('张秀华','女',68),('顾会','女',50)," +
"('赵天一','男',32)";
int i = stat.executeUpdate(s);
System.out.print(i);
}
public static void method1(Statement stat) throws SQLException
{
String s = "select * from studb where i_sex = '女' and score > 80";
ResultSet rs = stat.executeQuery(s);
while(rs.next())
{
String ss = rs.getString("i_name");
String sex = rs.getString("i_sex");
int i = rs.getInt("score");
System.out.println(ss+" "+sex+" "+i);
}
}
public static void method2(Statement stat) throws SQLException
{
String s = "update studb set score = 100 where i_sex = '男' and i_name like '张%'";
int i = stat.executeUpdate(s);
System.out.print(i);
}
public static void method3(Statement stat) throws SQLException
{
String s = "selext * from studb where i_age > 20 and i_sex = '女'";
ResultSet rs = stat.executeQuery(s);
while(rs.next())
{
String name = rs.getString("i_name");
String sex = rs.getString("i_sex");
int i = rs.getInt("score");//把score改成age就行
System.out.println(name+" "+sex+" "+i);
}
}
}