
- 只是实现一些基本 *** 作,这里面需要加载数据库驱动mysql
package h1;
import java.sql.*;
import java.util.*;
public class Ex1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Statement sta = null;
Connection con = null;
ResultSet res = null;
PreparedStatement pre = null;
try {
Class.forName("com.mysql.jdbc.Driver");//������ݿ�����
String url = "jdbc:mysql://localhost:8008/myschool?useUnicode=true&characterEncoding=utf-8";
//?useUnicode=true&characterEncoding=utf-8这里加上这个utf-8是为了传数据库mysql不出现中文乱码
String user = "root";
String password = "";
con = DriverManager.getConnection(url,user,password);
sta = con.createStatement();
String sql1 = "select * from student";
//2.创建Statement对象并设置常量
Statement st =con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
//3.执行SQL并将获取的数据信息存放在ResultSet中
ResultSet rs = st.executeQuery(sql1);
//4.取出ResultSet中指定数据的信息
System.out.print("第2条数据的name值为:");
rs.absolute(2); //将指针定位到结果集中第2行数据
System.out.println(rs.getString("stuName"));
System.out.print("第1条数据的name值为:");
rs.beforeFirst(); //将指针定位到结果集中第1行数据之前
rs.next(); //将指针向后滚动
System.out.println(rs.getString("stuName"));
System.out.print("第4条数据的name值为:");
rs.afterLast(); //将指针定位到结果集中最后一条数据之后
rs.previous(); //将指针向前滚动
System.out.println(rs.getString("stuName"));
String sql2 = "INSERT INTO student(stuId,stuName,stuAge)"
+ "VALUES(?,?,?)";
pre = con.prepareStatement(sql2);
pre.setInt(1,10);
pre.setString(2,"张思");
pre.setInt(3,25);
pre.executeUpdate();//执行sql语句
res = sta.executeQuery(sql1);
System.out.println("StudentID || StudentName || StudentAge ");
//执行RESult结果收集
while (res.next()) {
int id = res.getInt("stuId");
String name = res.getString("stuName");
int age = res.getInt("stuAge");
System.out.println(id+"tt"+name+"tt"+age);
}
//定位查找sql数据
String sql3 = "select * from student where stuId = 2";
System.out.println("StudentID || StudentName || StudentAge ");
res = sta.executeQuery(sql3);
while(res.next()) {
int id = res.getInt("stuId");
String name = res.getString("stuName");
int age = res.getInt("stuAge");
System.out.println(id+"tt"+name+"tt"+age);
}
//删除指定sql数据
String sql4 = "delete from student where stuId=5";
int index = sta.executeUpdate(sql4);
// 5. *** 作ResultSet结果集
if(index > 0){
System.out.println("删除成功");
}
//修改指定sql数据
String sql5 = "update student set stuName='张思' where stuId=6";
int index1 = sta.executeUpdate(sql5);
// 5. *** 作ResultSet结果集
if(index1 > 0){
System.out.println("修改成功");
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
if (sta != null) {
try {
sta.close();
} catch (Exception e) {
e.printStackTrace();
}
sta = null;
}
if (con != null) {
try {
con.close();
} catch (Exception e) {
e.printStackTrace();
}
con = null;
}
if (res != null) {
try {
res.close();
} catch (Exception e) {
e.printStackTrace();
}
res = null;
}
}
}
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)