Common techniques for Java database programming

Source: Internet
Author: User

Java database Operation basic process: Get database connection-Execute SQL statement-Process Execution result-release database connection

1. Get the database connection

1 Use DriverManager to access the database connection, example:

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) using Jndi (Java naming and directory services), examples:

String jndi = "jdbc/db";
  Context ctx =
(Context) new InitialContext().lookup 
("Java:comp/env");
  DataSource ds = (DataSource) ctx.lookup(jndi);
  Connection cn = ds.getConnection();

More used in JSP

2. Execute SQL statement

1 using statement to execute SQL statements

String sql;
Statement sm = cn.createStatement();
sm.executeQuery(sql);
// 执行数据查询语句(select)
sm.executeUpdate(sql);
// 执行数据更新语句
(delete、update、insert、drop等)
statement.close();

2 using PreparedStatement to execute SQL statements

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();
// 更新

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.