package test_connect;
import java.sql.*;
public class testDB {
public static void main(String[] args) throws Exception {
String driverName="com.microsoft.sqlserver.jdbc.SQLServerDriver";
String dbURL="jdbc:sqlserver://127.0.0.1:1433;DatabaseName = eBookShopDB";//test为你的数据库名
String userName="sa";//你的数据库用户名
String userPwd="qwe12580";//你的密码
ResultSet rs = null;
ResultSet rs2 = null;
Statement stmt = null;
Connection Conn = null;
// 1.加载驱动
try {
Class.forName(driverName);
System.out.println("加载驱动成功!");
} catch (Exception e) {
e.printStackTrace();
System.out.println("加载驱动失败!");
}
// 2.连接数据库
try {
Conn = DriverManager.getConnection(dbURL,userName,userPwd);
System.out.println("连接数据库成功!");
} catch (Exception e) {
e.printStackTrace();
System.out.print("SQL Server连接失败!");
}
// 3.基本操作:执行SQL语句
try {
// 3.1获得执行SQL语句的对象
stmt = Conn.createStatement();
// 3.2编写SQL语句
String sql = "select * from dbo.订单";
// 3.3执行SQL:executeQuery执行查询
rs = stmt.executeQuery(sql);
while(rs.next()) {
System.out.print(rs.getString("客户编号")+" ");
System.out.print(rs.getString("金额")+" ");
System.out.println();
}
String sql2 = "update dbo.图书信息 set 译者 = 'testt' where ISBN编号 = '9787040217322'";
rs2 = stmt.executeQuery(sql2);
int count = stmt.executeUpdate(sql2);
System.out.print(count);
} catch (Exception e) {
e.printStackTrace();
System.out.println("SQL Server 获取表信息失败!");
}finally{
// 4.释放资源
// 标准资源释放的代码
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (rs2 != null) {
try {
rs2.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
stmt = null;
}
if (Conn != null) {
try {
Conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
Conn = null;
}
}
}
}
查询没问题,sql2做一个更新的操作就异常了
更新 不能调这个 executeQuery,要调 executeUpdate
USE mydb;
CREATE TABLE USER(
NAME VARCHAR(50) PRIMARY KEY,
passwd VARCHAR(50)
);
INSERT INTO USER (NAME,passwd) VALUES ('jack','123456');
package bull02.JDBCUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import org.junit.Test;
public class PreparedDemo {
@Test
public void method() {
String name = "jack #";
String passwd = "123456";
Connection conn = null;
PreparedStatement psmt = null;
ResultSet rs = null;
try {
//获得连接
conn = JDBCUtils.getConnections();
//获取SQL语句
String sql = "select * from user where name = ? and passwd = ?";
//获得预处理对象
psmt = conn.prepareStatement(sql);
//设置实际参数
psmt.setString(1, name);
psmt.setString(2, passwd);
//执行
rs = psmt.executeQuery();
if(rs.next()) {
System.out.println("登录成功!");
}
else {
System.out.println("登录失败!");
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
JDBCUtils.closeResource(conn, psmt, rs);
}
}
}