import java.sql.ResultSet; //都是导入一些下面需要用到的类
创新互联服务项目包括山丹网站建设、山丹网站制作、山丹网页制作以及山丹网络营销策划等。多年来,我们专注于互联网行业,利用自身积累的技术优势、行业经验、深度合作伙伴关系等,向广大中小型企业、政府机构等提供互联网行业的解决方案,山丹网站推广取得了明显的社会效益与经济效益。目前,我们服务的客户以成都为中心已经辐射到山丹省份的部分城市,未来相信会继续扩大服务区域并继续获得客户的支持与信任!
String ConnStr="jdbc:microsoft:sqlserver://WINJUE:1433;DatabaseName=library";//jdbc连接数据库url
public sqlServer() {
try {
Class.forName(DBDriver).newInstance(); //加载SQLServer驱动程序,DBDriver是你上面的代码;
conn=DriverManager.getConnection(ConnStr,"sa","sa"); //和数据库建立连接,ConnStr里面的://WINJUE:1433;DatabaseName=library 分别是主机地址:端口号;你自己建的数据库(database)
}
catch(SQLException e) { //捕获SQL异常
System.out.println(e.getMessage()); //要是出现异常,捕获到后,这句代码会把异常的信息(出错的原因之类的)打印出来。
}
catch(Exception e) { //捕获异常,这个是总的,所以不能和上面的顺序颠倒,先小到大,我连ORACLE和MYSQL,这个我通常不要,只须捕获SQL异常就OL
System.out.println(e.getMessage());
}
}
public Connection getConn(){ //获取连接方法
return conn;
}
public void insert(String sql) {//增删改
try {
Statement stm=conn.createStatement(); 调用conn下的方法,创建Statement对象
stm.executeUpdate(sql);//调用Statement下的方法执行SQL语句
System.out.println("操作成功");
}
catch(Exception e){
System.out.println(e.getMessage()); //如上
}
}
public ResultSet query(String sql){ //查询
try{
Statement stm=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
rs=stm.executeQuery(sql); //如上
}
catch(Exception e){
System.out.println(e.getMessage());
}
return rs;
}
public static void main(String args[]){
sqlServer conn=new sqlServer(); //创建sqlServer,就是你上面的类,以便调用里面的方法
ResultSet rs=conn.query("select * from Orders"); //调用query方法,执行SQL语句后,把结果保存到结果集里
//conn.insert("delete from BookInfo where BookName =" +"\'悟空传\'");
//conn.insert("insert into BookInfo (BookID,BookName,Author,KeyWord) values (14445678,'悟空传','今何在','孙悟空')");
try{
while(rs.next()){ //循环,判断结果集里的记录,一条条往下走,是否还有下一条记录,若是返回真,继续走
System.out.print(rs.getString("OrderID"));
//System.out.print(rs.getString("U_age"));
}
rs.close() ; //关闭结果集
}
catch (Exception e){
System.out.println(e.getMessage());
}
}
}
注:
TYPE_FORWARD_ONLY:缺省类型。只允许向前访问一次,并且不会受到其他用户对该数据库所作更改的影响。
TYPE_SCROLL_INSENSITIVE:允许在列表中向前或向后移动,甚至能进行特定定位,例如移至列表中的第四个记录或从当前位置向后移动两个记录。不会受到其他用户对该数据库所作更改的影响。
TYPE_SCROLL_SENSITIVE:象 TYPE_SCROLL_INSENSITIVE 相同,允许在记录中定位。这种类型受到其他用户所作更改的影响。如果用户在执行完查询之后删除一个记录,那个记录将从 ResultSet 中消失。类似的,对数据值的更改也将反映在 ResultSet 中。
这个是连接sql server 2000的数据库的
package com.bling.sql1;
import java.sql.*;
public class SqlTest
{
private String drive="com.microsoft.jdbc.sqlserver.SQLServerDriver";
private String url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=BLing";
private String user="sa";
private String pass="84004880";
private Connection connect;
private Statement state;
private ResultSet result;
public SqlTest()
{
try
{
Class.forName(drive);
connect=DriverManager.getConnection(url,user,pass);
state=connect.createStatement();
result=state.executeQuery("select * from Blingkk");
while(result.next())
{
System.out.println(result.getString("username"));
System.out.println(result.getString("password"));
}
state.close();
connect.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
new SqlTest();
}
}
package com.conn;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
public class ConPool {
private String strDriverClass;
private String strJdbcUrl;
private String strUserName;
private String strUserPwd;
public ConPool(){
}
public Connection getMyJdbcConn()
{
Connection myConn=null;
try {
Class.forName(this.getStrDriverClass()).newInstance();
//DriverManager.registerDriver (new org.postgresql.Driver());
myConn= DriverManager.getConnection(this.getStrJdbcUrl(),this.getStrUserName(),this.getStrUserPwd());
}catch (Exception ex) {
System.out.print(ex);
}
return myConn;
}
public void closeConn(Connection myConn)
{
if (myConn!=null) {
try{
myConn.close();
myConn=null;
}catch(Exception e){}
}
}
/**
* @return the strDriverClass
*/
public String getStrDriverClass() {
return strDriverClass;
}
/**
* @param strDriverClass the strDriverClass to set
*/
public void setStrDriverClass(String strDriverClass) {
this.strDriverClass = strDriverClass;
}
/**
* @return the strJdbcUrl
*/
public String getStrJdbcUrl() {
return strJdbcUrl;
}
/**
* @param strJdbcUrl the strJdbcUrl to set
*/
public void setStrJdbcUrl(String strJdbcUrl) {
this.strJdbcUrl = strJdbcUrl;
}
/**
* @return the strUserName
*/
public String getStrUserName() {
return strUserName;
}
/**
* @param strUserName the strUserName to set
*/
public void setStrUserName(String strUserName) {
this.strUserName = strUserName;
}
/**
* @return the strUserPwd
*/
public String getStrUserPwd() {
return strUserPwd;
}
/**
* @param strUserPwd the strUserPwd to set
*/
public void setStrUserPwd(String strUserPwd) {
this.strUserPwd = strUserPwd;
}
public static void main(String[] args) {
Connection crmCon=null;
ConPool cp = new ConPool();
// //MySQL数据库
// cp.setStrDriverClass("com.mysql.jdbc.Driver");
// cp.setStrJdbcUrl("jdbc:mysql://127.0.0.1:3306/test?useUnicode=truecharacterEncoding=gbk");
// cp.setStrUserName("test");
// cp.setStrUserPwd("test");
//postgre数据库
cp.setStrDriverClass("org.postgresql.Driver");
cp.setStrJdbcUrl("jdbc:postgresql://127.0.0.1:5432/test");
cp.setStrUserName("test");
cp.setStrUserPwd("test");
crmCon=cp.getMyJdbcConn();
if (crmCon!=null) {
System.out.println("通过jdbc连接成功!");
}
// try {
// Statement stmtCrmUpd = crmCon.createStatement();
//
// stmtCrmUpd.addBatch("truncate table trade.sms_tmp_feild ");
// stmtCrmUpd.addBatch("INSERT INTO trade.sms_tmp_feild VALUES (0, 'membername', '%s', '会员姓名')");
// stmtCrmUpd.addBatch("INSERT INTO trade.sms_tmp_feild VALUES (1, 'cardwh', '%s', '卡号末四位')");
// stmtCrmUpd.addBatch("INSERT INTO trade.sms_tmp_feild VALUES (2, 'transmerchant', '%s', '交易店')");
// stmtCrmUpd.addBatch("INSERT INTO trade.sms_tmp_feild VALUES (3, 'transtype', '%s', '交易类型')");
// stmtCrmUpd.addBatch("INSERT INTO trade.sms_tmp_feild VALUES (4, 'transamount', '%.2f', '交易金额')");
// stmtCrmUpd.addBatch("INSERT INTO trade.sms_tmp_feild VALUES (5, 'cardbalance', '%.2f', '卡余额')");
// stmtCrmUpd.addBatch("INSERT INTO trade.sms_tmp_feild VALUES (6, 'merchantbrand', '%s', '交易商户集团名称')");
// stmtCrmUpd.addBatch("INSERT INTO trade.sms_tmp_feild VALUES (7, 'couponname', '%s', '券名称')");
// stmtCrmUpd.addBatch("INSERT INTO trade.sms_tmp_feild VALUES (9, 'cardno', '%s', '卡号')");
// stmtCrmUpd.addBatch("INSERT INTO trade.sms_tmp_feild VALUES (10, 'cardmerchant', '%s', '卡属商户名')");
// stmtCrmUpd.addBatch("INSERT INTO trade.sms_tmp_feild VALUES (11, 'transdate', '%tm月%te日', '交易日期')");
// stmtCrmUpd.addBatch("INSERT INTO trade.sms_tmp_feild VALUES (12, 'transtime', '%tT', '交易时间')");
//
// crmCon.setAutoCommit(false);
// //成功的话再提交保存当前最大ID号和失败日志
// stmtCrmUpd.executeBatch();
// crmCon.commit();
// crmCon.setAutoCommit(true);
//
// }catch (Exception ex) {
// System.out.println("数据库执行异常!");
// System.out.println(ex);
// try {
// crmCon.rollback();
// }catch (Exception e) {
// System.out.println("数据库回滚异常!");
// System.out.println(e);
// }
// }
//
// ResultSet rset = null;
//
// String sql = "select field_name,field_type from trade.sms_tmp_feild";
// MapString,String m = new HashMapString,String();
// try {
// Statement stmtCrm = crmCon.createStatement();
// rset = stmtCrm.executeQuery(sql);
//
// if (rset!=null){
// while (rset.next()){
// m.put(rset.getString("field_name"), rset.getString("field_type"));
// }
// rset.close();
// }
// rset = null;
// stmtCrm.close();
// stmtCrm = null;
// }catch (Exception ex) {
// System.out.println("数据库执行异常!");
// System.out.println(ex);
// }
//
//
// String strSql = "SELECT id,replace(replace(replace(replace(replace(replace(message_template,'tm月%te日',''),'d',''),'.2f',''),'tF',''),'tT',''),'s','') as message_template," +
// "template_feilds FROM trade.message_template";
//
// try {
// Statement stmtCrm = crmCon.createStatement();
// Statement stmtCrmUpd = crmCon.createStatement();
// rset = stmtCrm.executeQuery(strSql);
//
// if (rset!=null){
// while (rset.next()){
// if (rset.getString("template_feilds")!=nullrset.getString("message_template")!=null){
// String[] aryFeild = rset.getString("template_feilds").split(",");
// String[] aryCon = rset.getString("message_template").split("%");
// String tid = rset.getString("id");
//
// if (aryFeild!=nullaryFeild.length0aryCon!=nullaryCon.length0){
// StringBuilder strB = new StringBuilder();
// StringBuilder strF = new StringBuilder();
// StringBuilder bSql = new StringBuilder();
// strB.append(aryCon[0]);
// for (int i=1;iaryCon.length;i++){
// String strFormatCon = m.get(aryFeild[i-1]);
// if (strFormatCon.indexOf("%", 1)0){
// strF.append(aryFeild[i-1]+",");
// }
// strF.append(aryFeild[i-1]+",");
// strB.append(strFormatCon);
// strB.append(aryCon[i]);
// }
//
// if (strF.lastIndexOf(",")==strF.length()-1){
// strF.delete(strF.length()-1, strF.length());
// }
// System.out.println("原模板内容:"+rset.getString("message_template"));
// System.out.println("新摸版内容:"+strB.toString());
// System.out.println("原模板字段:"+rset.getString("template_feilds"));
// System.out.println("新模板字段:"+strF.toString());
//
// bSql.append("update trade.message_template set message_template='"+strB.toString()+"',template_feilds='"+strF.toString()+"' where id="+tid);
//
// System.out.println("修改模板Sql:"+strF.toString());
//
// stmtCrmUpd.addBatch(bSql.toString());
// }
// }
// }
// rset.close();
// }
// rset = null;
// stmtCrm.close();
// stmtCrm = null;
//
// crmCon.setAutoCommit(false);
// stmtCrmUpd.executeBatch();
// crmCon.commit();
// crmCon.setAutoCommit(true);
//
// stmtCrmUpd.close();
// stmtCrmUpd = null;
// }catch (Exception ex) {
// System.out.println("数据库执行异常!");
// System.out.println(ex);
// try {
// crmCon.rollback();
// }catch (Exception e) {
// System.out.println("数据库回滚异常!");
// System.out.println(e);
// }
// }
cp.closeConn(crmCon);
}
}
import java.sql.Connection。
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class DBCon {
//数据库驱动对象
public static final String DRIVER="oracle.jdbc.driver.OracleDriver";
//数据库连接地址(数据库名)
public static final String URL="jdbc:oracle:thin:@localhost:1521:orcl";
//登陆名
public static final String USER="FM";
//登陆密码
public static final String PWD="FM";
//创建数据库连接对象
private Connection con=null;
//创建数据库预编译对象
private PreparedStatement ps=null;
//创建结果集
private ResultSet rs=null;
//创建数据源对象
public static DataSource source=null;
// //静态代码块
// static{
//
// //初始化配置文件context
// try {
// Context context=new InitialContext();
// source=(DataSource)context.lookup("java:comp/env/jdbc/webmessage");
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
//
// }
/**
* 获取数据库连接
*/
public Connection getCon(){
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
con=DriverManager.getConnection(URL,USER,PWD);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}
// /**
// * 获取数据库连接
// */
// public Connection getCon(){
//
// try {
// con=source.getConnection();
// } catch (SQLException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
// return con;
// }
/**
* 关闭所有资源
*/
public void closeAll(){
if(rs!=null)
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(ps!=null)
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(con!=null)
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* @param sql数据库更新(增、删、改) 语句
* @param pras参数列表(可传,可不传,不传为NULL,以数组形式存在)
* @return 返回受影响都行数
*/
public int update(String sql,String... pras){
int resu=0;
con=getCon();
try {
ps=con.prepareStatement(sql);
for(int i=0;ipras.length;i++){
ps.setString(i+1,pras[i]);
}
resu=ps.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
closeAll();
}
return resu;
}
/**
* @param sql数据库查询语句
* @param pras参数列表(可传,可不传,不传为NULL,以数组形式存在)
* @return 返回结果集
*/
public ResultSet query(String sql,String... pras){
con=getCon();
try {
ps=con.prepareStatement(sql);
if(pras!=null)
for(int i=0;ipras.length;i++){
ps.setString(i+1, pras[i]);
}
rs=ps.executeQuery();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rs;
}
}
in thread "main" java.lang.Error: Unresolved compilation problem:一般是说没有导包..
第一:你看看text1文件在那个包下面..比如我的是在test这个包下(package test);
package test;
public class Test {
}
dbConn = DriverManager.getConnection(dbURL,username,password);
Connection dbConn;
第二;你这里有问题..应该去掉dbConn = DriverManager.getConnection(dbURL,username,password);因为你没有加载驱动是不能这样调用的;
第三:你那些数据库驱动jar包导入了没有啊
用这个类吧.好的话,给我加加分.
import java.sql.*;
/**
* @功能: 一个JDBC的本地化API连接类,封装了数据操作方法,只用传一个SQL语句即可
* @作者: 李开欢
* @日期: 2007/
*/
public class ConnectionDemo {
/*
* 这里可以将常量全部放入另一个类中,以方便修改
*/
private static Connection conn;
private static Statement ps;
private static ResultSet rs;
private static final String DRIVER = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
private static final String URL = "jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=mydb";
private static final String USER ="sa";
private static final String PASS = "sa";
public ConnectionDemo() {
// TODO Auto-generated constructor stub
ConnectionDemo.getConnection();
}
public static Connection getConnection(){
System.out.println("连接中...");
try {
Class.forName(ConnectionDemo.DRIVER);
conn = DriverManager.getConnection(ConnectionDemo.URL, ConnectionDemo.USER, ConnectionDemo.PASS);
System.out.println("成功连接");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
public static Statement getStatement(String sql){
System.out.println("执行SQL语句中...");
try {
ps = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
if(sql.substring(0, 6).equals("select")){
rs = ps.executeQuery(sql);
System.out.println("执行完查询操作,结果已返回ResultSet集合");
}else if(sql.substring(0, 6).equals("delete")){
ps.executeUpdate(sql);
System.out.println("已执行完毕删除操作");
}else if(sql.substring(0, 6).equals("insert")){
ps.executeUpdate(sql);
System.out.println("已执行完毕增加操作");
}else{
ps.executeUpdate(sql);
System.out.println("已执行完毕更新操作");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ps;
}
public static ResultSet getResultSet(){
System.out.println("查询结果为:");
return rs;
}
public static void closeConnection(){
System.out.println("关闭连接中...");
try {
if (rs != null) {
rs.close();
System.out.println("已关闭ResultSet");
}
if (ps != null) {
ps.close();
System.out.println("已关闭Statement");
}
if (conn != null) {
conn.close();
System.out.println("已关闭Connection");
}
} catch (Exception e) {
// TODO: handle exception
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ConnectionDemo.getConnection();
String sql = "delete from type where id = 1";
ConnectionDemo.getStatement(sql);
String sql2 = "insert into type values(1,'教学设备')";
ConnectionDemo.getStatement(sql2);
String sql1 = "select * from type";
ConnectionDemo.getStatement(sql1);
ResultSet rs = ConnectionDemo.getResultSet();
System.out.println("编号 "+"类 型");
try {
while(rs.next()){
System.out.print(" "+rs.getInt(1)+" ");
System.out.println(rs.getString(2));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ConnectionDemo.closeConnection();
}
}