很多数据库的初学者学了不少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();
}
}