数据库连接 和 动态查询
package executeQueryDemo1;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class queryDemo {
protected static String dbClassName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
static final String dbUrl = "jdbc:sqlserver://localhost:1433;databaseName=StudentManager";
protected static String dbUser = "sa";
protected static String dbPwd = "123";
protected static String second = null;
private static Connection conn = null;
public queryDemo() {
try {
if (conn == null) {
Class.forName(dbClassName).newInstance();
conn = DriverManager.getConnection(dbUrl, dbUser, dbPwd);
String sql= "select * from stu where Sname like ?"; // 通配符“?”
PreparedStatement pStatement = conn.prepareStatement(sql);
pStatement.setString(1, "邢%"); // 参数序号 参数值
ResultSet rSet = pStatement.executeQuery();
System.out.println("学号"+"\t"+"姓名"+"\t"+"性别"+"\t"+"年龄"+"\t"+"籍贯"+"\t"+"系部");
while(rSet.next()) {
System.out.println(rSet.getString(1)+"\t"+rSet.getString(2)+"\t"+rSet.getString(3)+"\t"+rSet.getInt(4)+"\t"+rSet.getString(5)+"\t"+rSet.getString(6));
}
}
else
return;
} catch (Exception ee) {
ee.printStackTrace();
}
}
private static ResultSet executeQuery(String sql) {
try {
if(conn==null)
new queryDemo();
return conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE).executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace();
return null;
} finally {
}
}
private static int executeUpdate(String sql) {
try {
if(conn==null)
new queryDemo();
return conn.createStatement().executeUpdate(sql);
} catch (SQLException e) {
System.out.println(e.getMessage());
//if(e.getMessage().equals("[Microsoft][SQLServer 2000 Driver for JDBC][SQLServer]DELETE 语句与 COLUMN REFERENCE 约束 'FK_TB_BORRO_REFERENCE_TB_BOOKI' 冲突。该冲突发生于数据库 'db_library',表 'tb_borrow', column 'bookISBN'。"))
return -1;
} finally {
}
}
public static void close() {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}finally{
conn = null;
}
}
public static void main(String[] args) {
new queryDemo();
}
}
鲜花会生锈,盐巴会腐烂