///几个重要的语句
String insertSql="insert into Product(name,price) values('"+name+"',"+price+")";//price 为整型
String updateSql="update Product set PName='"+name+"', PPrice="+price+" where PID='"+id+"'";
String sql="select * from Product where PName like '%"+key+"%'";
String sql = "delete t_user where userid="+userid;
JNDI方法一
/////////////////////////////////////////
记得导入6个.JAR包并在tomcat中的lib文件下也要导入这6个.JAR包
工具类
package util;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import com.Admin;
/**
* @author wsq
* @version 1.0 07/10/20
*/
public class DBConnection {
private static Connection con = null;
private static Statement stmt = null;
private static ResultSet rs = null;
private static ArrayList<String[]> ArrayRs = null;
/**
*
* 创建数据源
*
* @return Connection
* @throws Exception
*/
public static synchronized Connection getConnection() throws Exception {
Context initCtx = new InitialContext(); // 从Context中lookup数据源。
DataSource ds = (DataSource) initCtx.lookup("java:comp/env/jdbc/data"); // jdbc/data为下面Resource的name属性
return ds.getConnection();
}
/**
*
* 执行数据查询操作
*
* @param sql
* @return ResultSet
*/
public static ArrayList executeQuery(String sql) {
try {
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
ResultSetMetaData rsmd = rs.getMetaData(); // 获取此 ResultSet 对象的列的编号、类型和属性。
int numberOfColumns = rsmd.getColumnCount();// 返回此 ResultSetMetaData对象中的列数。
// 判断是否为空
if (!ArrayRs.isEmpty()) {
ArrayRs.clear();
}
/*
* 将每条记录写入数组 将数组放在ArrayList里
*/
while (rs.next()) {
String[] strArrayTemp = new String[numberOfColumns];
for (int i = 0; i < numberOfColumns; i++) {
if (rs.getObject(i + 1) == null) {
strArrayTemp[i] = "";
} else {
strArrayTemp[i] = rs.getObject(i + 1).toString();// 以
// Java
// 编程语言中
// Object
// 的形式获取此
// ResultSet
// 对象的当前行中指定列的值;
// 第一个列是1,第二个列是2,....
System.out.println(" test value " + strArrayTemp[i]);
}
}
ArrayRs.add(strArrayTemp);
}
System.out.println("executeQuery successfully!");
return (ArrayList) ArrayRs.clone();
} catch (SQLException ex) {
System.out.println("query error:" + ex.getMessage());
} finally {
DBConnection.close();
}
return ArrayRs;
}
/**
* @param executeInsert插入数据方法
* @return 插入条数是否成功(boolean)
*/
public static boolean executeInsert(String strSql) throws SQLException {
rs = null;
try {
con = DBConnection.getConnection();
stmt = con.createStatement();
con.setAutoCommit(true);
int i = stmt.executeUpdate(strSql);
if (i == 1) {
return (true);
}
} catch (Exception e) {
System.out.println("Insert error:" + e.getMessage());
} finally {
DBConnection.close();
}
return (false);
}
/**
* 执行数据更新操作
*
* @param sql
* @return 更新是否成功 (int)
* @throws Exception
*/
public static int executeUpdate(String sql) throws Exception {
int result = 0;
con = DBConnection.getConnection();
try {
Statement stmt = con.createStatement();
result = stmt.executeUpdate(sql);// 返回影响的行数
con.commit(); // 提交
} catch (SQLException ex) {
try {
con.rollback();// 回滚
} catch (SQLException e) {
System.out.println("update error:" + e.getMessage());
}
System.err.println(ex.getMessage());
} finally {
DBConnection.close();
}
return result;
}
/**
* @param executeDelete删除数据方法
* @return 删除数据数(int)
*/
public static int executeDelete(String strSql) throws SQLException {
rs = null;
int j = 0;
try {
con = DBConnection.getConnection();
stmt = con.createStatement();
con.setAutoCommit(false);
j = stmt.executeUpdate(strSql);
if (j > 0) {
con.commit();
} else {
con.rollback();
}
} catch (Exception e) {
System.out.println("Delete error:" + e.getMessage());
} finally {
DBConnection.close();
}
return j;
}
/**
*
* 关闭连接,将连接送回连接池
*
*/
public static void close() {
if (con != null) {
try {
con.close();
con = null;
} catch (SQLException ex) {
System.err.println(ex.getMessage());
}
}
}
}
在项目的...\WebRoot\META-INF下创建个context.xml或者在tomcat中的server.xml写
<Context path="/jndi" docBase="jndi" debug="0" reloadable="true" crossContext="true">
<Resource name="jdbc/data" auth="Container" type="javax.sql.DataSource"
driverClassName="com.microsoft.jdbc.sqlserver.SQLServerDriver"
url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=dbs"
username="wsq" password="123" maxIdle="20" maxWait="5000"
maxActive="100" removeAbandoned="true"
removeAbandonedTimeout="60" logAbandoned="true"/>
</Context>
方法二
Struts(1.2)
/////////////////////////
连接池在struts-cionfig.xml中的配置(sql2000)
<data-sources>
<data-source type="org.apache.commons.dbcp.BasicDataSource" key="data'>
<set-property property="driverClassName"value="com.microsoft.jdbc.sqlserver.SQLServerDriver" />//记得要Name
<set-property property="url"value="jdbc:microsoft:sqlserver://localhost:1433;databasename=dbs" />
<set-property property="username" value="wsq" />//记得要name
<set-property property="password" value="123" />
<set-property property="maxActive" value="10" />
<set-property property="maxWait" value="5000" />
<set-property property="defaultAutoCommit" value="false" />//记得在false的情况(插入和更新时要con.commit)
<set-property property="defaultReadOnly" value="false" />
</data-source>
</data-sources>
/////////////////////////////////////////////////////////
辅助类
package tools;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
public class DBUtil {
Connection con=null;
ResultSet rs = null;
public DBUtil(DataSource dataSource)
{
try {
con=dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
}
////在数据库中执行查询操作
public ResultSet executeQuery(String sql) {
try {
Statement stmt = con.createStatement();
rs = stmt.executeQuery(sql);
}
catch(SQLException ex) {
ex.printStackTrace();
}
return rs;
}
// 在数据库中执行数据更新的方法
public int executeUpdate(String sql) {
int result = 0;
try {
Statement stmt = con.createStatement();
//返回影响的行数
result = stmt.executeUpdate(sql);
}
catch(SQLException ex) {
try {
con.rollback(); //回滚
} catch (SQLException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
System.err.println(ex.getMessage());
}
return result;
}
// 关闭数据源
public void close(){
if(con!=null){
try{
con.close();
con = null;
}catch(SQLException ex) {
System.err.println(ex.getMessage());
}
}
}
}
//////////////////////////////////////////////////////////////////////////////////////
(不利用辅助类时)
在xxxAction.java中的execute()方法中
try{
DataSource dataSource=getDataSource(request,"data");//得到数据源
//得到数据源ServletContext context=servlet.getServletContext();
// DataSource dataSource=(DataSource) context.getAttribute("data");
Connetion con=dataSource.getConnection();
PreparedStatement pstm=con.prepareStatement("insert into userone (name,password) values(?,?)");
pstm.setString(1,name);
pstm.setString(2,password);
pstm.executUpadate();
con.commit();/////记得写上(在插入或更新时一定要记得加上)正确是提交事务
} catch (SQLException e) {
con.rollback();//失败时回滚
e.printStackTrace();
}
finally{
pstm.close();
con.close();
}
方法三(最原始的)直接连
**********************
1. MySQL(http://www.mysql.com)mm.mysql-2.0.2-bin.jar/
Class.forName( "org.gjt.mm.mysql.Driver" );
cn = DriverManager.getConnection(
"jdbc:mysql://MyDbComputerNameOrIP:3306/myDatabaseName", sUsr, sPwd );
2. PostgreSQL(http://www.de.postgresql.org)pgjdbc2.jar/
Class.forName( "org.postgresql.Driver" );
cn = DriverManager.getConnection(
"jdbc:postgresql://MyDbComputerNameOrIP/myDatabaseName", sUsr, sPwd );
3. Oracle(http://www.oracle.com/ip/deploy/database/oracle9i/)classes12.zip
Class.forName( "oracle.jdbc.driver.OracleDriver" );
cn = DriverManager.getConnection(
"jdbc:oracle:thin:@MyDbComputerNameOrIP:1521:ORCL", sUsr, sPwd );
4. Sybase(http://jtds.sourceforge.net)jconn2.jar/
Class.forName( "com.sybase.jdbc2.jdbc.SybDriver" );
cn = DriverManager.getConnection(
"jdbc:sybase:Tds:MyDbComputerNameOrIP:2638", sUsr, sPwd );
//(Default-Username/Password: "dba"/"sql")
5. Microsoft SQLServer(http://jtds.sourceforge.net/)
Class.forName( "net.sourceforge.jtds.jdbc.Driver" );
cn = DriverManager.getConnection(
"jdbc:jtds:sqlserver://MyDbComputerNameOrIP:1433/master", sUsr, sPwd );
6. Microsoft SQLServer(http://www.microsoft.com/)
Class.forName( "com.microsoft.jdbc.sqlserver.SQLServerDriver" );
cn = DriverManager.getConnection(
"jdbc:microsoft:sqlserver://localhost:1433;databaseName=dbs", sUsr, sPwd );
7. ODBC
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
Connection cn = DriverManager.getConnection( "jdbc:odbc:" + sDsn, sUsr, sPwd
);
select @@version 是查看你的MSSQL版本 看补丁打没打
///////////////////////////////////////////////////////////////////////////////////
String insertSql="insert into Product values('"+id+"','"+name+"',"+price+")";
String updateSql="update Product set PName='"+name+"', PPrice="+price+" where PID='"+id+"'";
String sql="select * from Product where PName like '%"+key+"%'";
String sql = "delete t_user where userid="+userid;
////////////////////////////////////////////////////////
posted on 2007-09-22 13:40
Crying 阅读(842)
评论(0) 编辑 收藏 所属分类:
数据库