新手学JAVA----走进JDBC
时间:2021-07-01 10:21:17
帮助过:22人阅读
java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
public class JDBCMain {
private Connection con =
null;
private Statement st =
null;
private ResultSet rs =
null;
public JDBCMain() {
try {
String driver =
"com.microsoft.sqlserver.jdbc.SQLServerDriver";
String ds =
"jdbc:sqlserver://localhost:1433;databaseName=JavaSpecial";
String user =
"sa";
String password =
"123456";
Class.forName(driver);
con = DriverManager.getConnection(ds, user, password);
if (con !=
null) {
System.out.println(
"数据库链接成功!");
}
}
catch (Exception e) {
System.out.println(
"数据库连接失败!" + e.toString());
}
}
/**
* 普通查询
* @param sqlQuery
*/
public void query(String sqlQuery) {
try {
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sqlQuery);
while (rs !=
null && rs.next()) {
int stu_num = rs.getInt(
1);
String name = rs.getString(
"name");
int age = rs.getInt(
"age");
int math = rs.getInt(
"math");
int english = rs.getInt(
"english");
System.out.println(
"学号=" + stu_num +
"\t 姓名=" + name +
"\t 年龄="
+ age +
"\t 数学成绩=" + math +
"\t 英语成绩=" + english);
}
}
catch (Exception e) {
System.out.println(
"查询数据时出错" + e.toString());
}
}
/**
* /添加,删除,更新
*/
public void add_update_Del(String sql) {
try {
Statement st = con.createStatement();
int x = st.executeUpdate(sql);
System.out.println(
"操作成功" + x);
}
catch (Exception e) {
System.out.println(
"数据修改时有误" + e.toString());
}
}
public static void main(String[] args) {
JDBCMain jc =
new JDBCMain();
String name =
"张三";
String sqlQuery =
"select * from stu_info where name=‘" + name +
"‘";
jc.query(sqlQuery);
String sqlAdd =
"insert into stu_info values(7,‘令仔‘,17,89,84)";
jc.add_update_Del(sqlAdd);
String sqlUpdate =
"update stu_info set math =95 where name =‘张三‘";
jc.add_update_Del(sqlUpdate);
String sqlDelete =
"delete from stu_info where name=‘张三‘";
jc.add_update_Del(sqlDelete);
}
}
下面是源代码下载的链接:JDBC数据库连接测试
版权声明:本文为博主原创文章,未经博主允许不得转载。
新手学JAVA----走进JDBC
标签:jdbc