当前位置:   article > 正文

java中嵌入sql语句_java嵌入sql

java嵌入sql

很多数据库的初学者学了不少sql语句,却知道在程序里怎么执行他们,这里以java为例,介绍一下java的嵌入sql语句

 

1.简单的链接数据库:

import java.sql.Connection;

import oracle.jdbc.pool.OracleDataSource;

public class TestConnection2 {

 public static void main(String[] args)throws Exception {
  OracleDataSource ods = new OracleDataSource();
//  ods.setURL("jdbc:oracle:thin:@localhost:1521:orcl");
//  ods.setUser("scott");
//  ods.setPassword("tiger");
  ods.setURL("jdbc:oracle:thin:scott/123@localhost:1521:orcl");
  
  Connection conn = ods.getConnection();
  System.out.println("连接成功,连接为:"+conn);
  conn.close();
 }
}

 

2.嵌入sql语句(假设有张表emp,有属性:empno,ename等):

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class TestConnection {

 public static void main(String[] args)throws ClassNotFoundException,SQLException {
  //4要素
  String driverName = "oracle.jdbc.driver.OracleDriver";
  driverName = "oracle.jdbc.OracleDriver";
  String url = "jdbc:oracle:thin:@localhost:1521:orcl";
  String username = "scott";
  String password = "123";
  
  //注册驱动获得连接
  Class.forName(driverName);
  Connection conn = DriverManager.getConnection(url,username,password);
   
  //获得语句对象
  Statement stmt = conn.createStatement();
  
  //发送sql语句
  String sql = "select empno,ename,sal from emp";
  ResultSet rs = stmt.executeQuery(sql);
  
  //解析结果
  while(rs.next()){
   String empno = rs.getString(1);
   String ename = rs.getString("ename");
   String sal = rs.getString(3);
   System.out.println(empno+" "+ename+" "+sal);
  }
  
  rs.close();
  stmt.close();
  conn.close();
 }
}

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/394746
推荐阅读
相关标签
  

闽ICP备14008679号