数据库,表的定义 以及表中的元素信息: JDBC基础1 查询和更新mysql数据库
java代码:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Test2 {
static final String user="root";//用户名
static final String pwd="";//密码
static final String database="test2";//要操作的数据库
static final String table="SC";
//数据库路径
static final String url="jdbc:mysql://localhost:3306/"+database+"?characterEncoding=UTF-8";
public static void main(String[] args) {
try
{
//加载驱动类;
Class.forName("com.mysql.jdbc.Driver");
//建立连接
Connection con=DriverManager.getConnection(url, user, pwd);
//生成命令执行器:
Statement stmt=con.createStatement();
//查询表
selectAllFromTable(stmt,table);
int score1=34;
String sid1="S1000";
String cid1="C002";
//更新成绩
updateScore(stmt,sid1,cid1,score1);
}
catch(Exception e)
{
System.out.println("异常哈哈哈哈!");
}
}
//查询表中全部信息
static void selectAllFromTable(Statement stmt,String table)
{
StringBuffer sql=new StringBuffer("select *from ");
sql.append(table);
sql.append(";");
//try语句执行之后会自动关闭资源 rs.close
try(ResultSet rs=stmt.executeQuery(sql.toString());)
{
// ResultSet rs=stmt.executeQuery(sql.toString());
System.out.println(table+" 表中的信息--------------------");
while (rs.next()) {
System.out.println("sid="+rs.getString(1)+"\tcid="+rs.getString(2)
+"\tscore="+rs.getString(3));
}
System.out.println("-----------------------------------");
}
catch(Exception exception)
{
System.out.println("查询错误");
}
}
//根据学号和课程号更新成绩
static void updateScore(Statement stmt,String sid1,String cid1,int score1)
{
StringBuffer sql=new StringBuffer("update ");
sql.append(table);
sql.append(" set score=");
sql.append(score1);
sql.append(" where cid='");
sql.append(cid1);
sql.append("' and sid='");
sql.append(sid1);
sql.append("';");
System.out.println(sql.toString());
//int executeUpdate(String sql)
//执行给定的SQL语句,这可能是 INSERT , UPDATE ,或 DELETE语句,
//或者不返回任何内容,如SQL DDL语句的SQL语句。
try {
System.out.println(stmt.executeUpdate(sql.toString()));
} catch (Exception e) {
System.out.println("更新失败!");
}
}
}
执行结果:
跟新之后的数据表: