import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
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);
}
}
} |