第3题
package databaseConn;
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 HomeWork1 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/myschool","root","84103");
String sql = "CREATE TABLE IF not EXISTS student(id INT(4),name VARCHAR(50));";
pst = conn.prepareStatement(sql);
pst.executeUpdate();
sql = "insert into student(id,name) value (?,?)";
pst = conn.prepareStatement(sql);
pst.setInt(1, 1);
pst.setString(2, "徐磊");
pst.executeUpdate();
rs=pst.executeQuery("select count(*) from student");
while(rs.next()) {
System.out.println("表中有:"+rs.getInt(1)+"条记录");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(conn!=null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
第4题
package databaseConn;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class HomeWork2 {
public static void main(String[] args) {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/myschool","root","84103");
st= conn.createStatement();
rs=st.executeQuery("select * from student");
System.out.println("id\t姓名");
while(rs.next()) {
System.out.println(rs.getInt("id")+"\t"+rs.getString("name"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(conn!=null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
第5题
package databaseConn;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
public class HomeWork3 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("请输入用户名:");
String name = in.next();
System.out.print("请输入密码:");
String password = in.next();
Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/epet", "root", "84103");
String sql = "select * from master where name = ?and password=?";
pst = conn.prepareStatement(sql);
pst.setString(1, name);
pst.setString(2, password);
rs = pst.executeQuery();
if (rs.next()) {
System.out.println("登录成功!");
} else {
System.out.println("登录失败!");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
in.close();
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}