2、几个常用的重要技巧:可滚动、更新的记录集 、 批量更新 、事务处理1、取得数据库连接1)用DriverManager取数据库连接例子:String className,url,uid,pwd
className = "oracle.jdbc.driver.OracleDriver"
url = "jdbc:oracle:thin:@127.0.0.1:1521:orasvr
uid = "system"
pwd = "manager"
Class.forName(className)
Connection cn = DriverManager.getConnection(url,uid,pwd)2)用jndi(java的命名和目录服务)方式例子String jndi = "jdbc/db"
Context ctx = (Context) new InitialContext().lookup("java:comp/env")
DataSource ds = (DataSource) ctx.lookup(jndi)
Connection cn = ds.getConnection() //多用于jsp中2、执行sql语句1)用Statement来执行sql语句String sql
Statement sm = cn.createStatement()
sm.executeQuery(sql)// 执行数据查询语句(select)
sm.executeUpdate(sql)// 执行数据更新语句(delete、update、insert、drop等)statement.close()2)用PreparedStatement来执行sql语句String sql
sql = "insert into user (id,name) values (?,?)"
PreparedStatement ps = cn.prepareStatement(sql)
ps.setInt(1,xxx)
ps.setString(2,xxx)
...
ResultSet rs = ps.executeQuery()// 查询
int c = ps.executeUpdate()// 更新3、处理执行结果查询语句,返回记录集ResultSet。更新语句,返回数字,表示该更新影响的记录数。ResultSet的方法:1、next(),将游标往后移动一行,如果成功返回true;否则返回false。2、getInt("id")或getSting("name"),返回当前游标下某个字段的值。3、释放连接。cn.close()一般,先关闭ResultSet,然后关闭Statement(或者PreparedStatement);最后关闭Connection可滚动、更新的记录集1、创建可滚动、更新的StatementStatement sm=cn.createStatement(ResultSet.TYPE_SCROLL_ENSITIVE,
ResultSet.CONCUR_READ_ONLY)该Statement取得的ResultSet就是可滚动的2、创建PreparedStatement时指定参数PreparedStatemet ps=cn.prepareStatement(sql,
ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY)ResultSet.absolute(9000)批量更新1、StatementStatement sm = cn.createStatement()
sm.addBatch(sql1)
sm.addBatch(sql2)
...
sm.executeBatch()一个Statement对象,可以执行多个sql语句以后,批量更新。这多个语句可以是delete、update、insert等或兼有2、PreparedStatementPreparedStatement ps = cn.preparedStatement(sql)
{
ps.setXXX(1,xxx)
...
ps.addBatch()
}
ps.executeBatch()一个PreparedStatement,可以把一个sql语句,变换参数多次执行,一次更新。事务的处理1、关闭Connection的自动提交cn.setAutoCommit(false)2、执行一系列sql语句要点:执行每一个新的sql语句前,上一次执行sql语句的Statement(或者PreparedStatemet)必须先closeStatement sm
sm = cn.createStatement(insert into user...)
sm.executeUpdate()
sm.close()sm = cn.createStatement("insert into corp...)
sm.executeUpdate()
sm.close()3、提交cn.commit()
从M$网站下载最新JDBC驱动或都使用maven:<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>9.4.1.jre11</version>
</dependency>
import java.sql.Connection
import java.sql.DriverManager
import java.sql.PreparedStatement
import java.sql.ResultSet
import java.sql.Statement
public class SQLDatabaseConnection {
// Connect to your database.
// Replace server name, username, and password with your credentials
public static void main(String[] args) {
String connectionUrl =
"jdbc:sqlserver://yourserver.database.windows.net:1433"
+ "database=AdventureWorks"
+ "user=yourusername@yourserver"
+ "password=yourpassword"
+ "encrypt=true"
+ "trustServerCertificate=false"
+ "loginTimeout=30"
String insertSql = "INSERT INTO SalesLT.Product (Name, ProductNumber, Color, StandardCost, ListPrice, SellStartDate) VALUES "
+ "('NewBike', 'BikeNew', 'Blue', 50, 120, '2016-01-01')"
ResultSet resultSet = null
try (Connection connection = DriverManager.getConnection(connectionUrl)
PreparedStatement prepsInsertProduct = connection.prepareStatement(insertSql, Statement.RETURN_GENERATED_KEYS)) {
prepsInsertProduct.execute()
// Retrieve the generated key from the insert.
resultSet = prepsInsertProduct.getGeneratedKeys()
// Print the ID of the inserted row.
while (resultSet.next()) {
System.out.println("Generated: " + resultSet.getString(1))
}
}
// Handle any errors that may have occurred.
catch (Exception e) {
e.printStackTrace()
}
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)