Home Database Mysql Tutorial Java数据库编程中的技巧_MySQL

Java数据库编程中的技巧_MySQL

Jun 01, 2016 pm 02:07 PM
sql implement Skill database renew programming statement

  1、java数据库操作基本流程

  2、几个常用的重要技巧:

  可滚动、更新的记录集

  批量更新

  事务处理

  java数据库操作基本流程:取得数据库连接 - 执行sql语句 - 处理执行结果 - 释放数据库连接

  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、创建可滚动、更新的Statement

  Statement 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、Statement

  Statement sm = cn.createStatement();
  sm.addBatch(sql1);
  sm.addBatch(sql2);
  ...
  sm.executeBatch()

  一个Statement对象,可以执行多个sql语句以后,批量更新。这多个语句可以是delete、update、insert等或兼有

  2、PreparedStatement

  PreparedStatement 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)必须先close

  Statement sm ;
  sm = cn.createStatement(insert into user...);
  sm.executeUpdate();
  sm.close();

  sm = cn.createStatement("insert into corp...);
  sm.executeUpdate();
  sm.close();

  3、提交

  cn.commit();

  4、如果发生异常,那么回滚

  cn.rollback();



Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Windows cannot access the specified device, path, or file Windows cannot access the specified device, path, or file Jun 18, 2024 pm 04:49 PM

A friend's computer has such a fault. When opening "This PC" and the C drive file, it will prompt "Explorer.EXE Windows cannot access the specified device, path or file. You may not have the appropriate permissions to access the project." Including folders, files, This computer, Recycle Bin, etc., double-clicking will pop up such a window, and right-clicking to open it is normal. This is caused by a system update. If you also encounter this situation, the editor below will teach you how to solve it. 1. Open the registry editor Win+R and enter regedit, or right-click the start menu to run and enter regedit; 2. Locate the registry "Computer\HKEY_CLASSES_ROOT\PackagedCom\ClassInd"

Windows permanently pauses updates, Windows turns off automatic updates Windows permanently pauses updates, Windows turns off automatic updates Jun 18, 2024 pm 07:04 PM

Windows updates may cause some of the following problems: 1. Compatibility issues: Some applications, drivers, or hardware devices may be incompatible with new Windows updates, causing them to not work properly or crash. 2. Performance issues: Sometimes, Windows updates may cause the system to become slower or experience performance degradation. This may be due to new features or improvements requiring more resources to run. 3. System stability issues: Some users reported that after installing Windows updates, the system may experience unexpected crashes or blue screen errors. 4. Data loss: In rare cases, Windows updates may cause data loss or file corruption. This is why before making any important updates, back up your

iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos Jul 18, 2024 am 05:48 AM

Apple's latest releases of iOS18, iPadOS18 and macOS Sequoia systems have added an important feature to the Photos application, designed to help users easily recover photos and videos lost or damaged due to various reasons. The new feature introduces an album called "Recovered" in the Tools section of the Photos app that will automatically appear when a user has pictures or videos on their device that are not part of their photo library. The emergence of the "Recovered" album provides a solution for photos and videos lost due to database corruption, the camera application not saving to the photo library correctly, or a third-party application managing the photo library. Users only need a few simple steps

Detailed tutorial on establishing a database connection using MySQLi in PHP Detailed tutorial on establishing a database connection using MySQLi in PHP Jun 04, 2024 pm 01:42 PM

How to use MySQLi to establish a database connection in PHP: Include MySQLi extension (require_once) Create connection function (functionconnect_to_db) Call connection function ($conn=connect_to_db()) Execute query ($result=$conn->query()) Close connection ( $conn->close())

How to handle database connection errors in PHP How to handle database connection errors in PHP Jun 05, 2024 pm 02:16 PM

To handle database connection errors in PHP, you can use the following steps: Use mysqli_connect_errno() to obtain the error code. Use mysqli_connect_error() to get the error message. By capturing and logging these error messages, database connection issues can be easily identified and resolved, ensuring the smooth running of your application.

How to use database callback functions in Golang? How to use database callback functions in Golang? Jun 03, 2024 pm 02:20 PM

Using the database callback function in Golang can achieve: executing custom code after the specified database operation is completed. Add custom behavior through separate functions without writing additional code. Callback functions are available for insert, update, delete, and query operations. You must use the sql.Exec, sql.QueryRow, or sql.Query function to use the callback function.

The Key to Coding: Unlocking the Power of Python for Beginners The Key to Coding: Unlocking the Power of Python for Beginners Oct 11, 2024 pm 12:17 PM

Python is an ideal programming introduction language for beginners through its ease of learning and powerful features. Its basics include: Variables: used to store data (numbers, strings, lists, etc.). Data type: Defines the type of data in the variable (integer, floating point, etc.). Operators: used for mathematical operations and comparisons. Control flow: Control the flow of code execution (conditional statements, loops).

Problem-Solving with Python: Unlock Powerful Solutions as a Beginner Coder Problem-Solving with Python: Unlock Powerful Solutions as a Beginner Coder Oct 11, 2024 pm 08:58 PM

Pythonempowersbeginnersinproblem-solving.Itsuser-friendlysyntax,extensivelibrary,andfeaturessuchasvariables,conditionalstatements,andloopsenableefficientcodedevelopment.Frommanagingdatatocontrollingprogramflowandperformingrepetitivetasks,Pythonprovid

See all articles