jdbc访问数据库
1.获取 驱动2.获取连接3.创建执行sql语句的处理器4.执行sql5.处理结果6.回收资源package com.rj1192.zyk;import java.sql.*;public class index {public static void main(String[] args) throws ClassNotFoundException, SQLException {//获取驱动Cl
·
需要先导入mysql-connector.jar 包
1.获取 驱动
2.获取连接 ----配置链接池,并从链接池获取连接,就是链接池技术
3.创建执行sql语句的处理器 ----
Statement stat = conn.createStatement(); 或者 preparedstatement
或者dbutil辅助类,接收不同类型的数据库查询结果
4.执行sql
5.处理结果
6.回收资源
import java.sql.*;
public class jdbc {
public static void main(String[] args) {
jdbc_selectone();
jdbc_update("mike",1,5000);
}
public static void jdbc_update(String name,int id ,int money){
Connection connection = null;
PreparedStatement pstat = null;
try {
//获得驱动
Class.forName("com.mysql.jdbc.Driver");
//获得链接
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/account", "root", "mysql");
//创建sql语句处理器prestatement或者statement
pstat = connection.prepareStatement("insert into account (id,name,money)values(?,?,?)");
pstat.setObject(1,id);
pstat.setObject(2,name);
pstat.setObject(3,money);
//执行sql语句
int a = pstat.executeUpdate();
System.out.println("成功修改了:"+a+"条数据");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
connection.close();
pstat.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void jdbc_selectone(){
Connection connection = null;
PreparedStatement pstat = null;
ResultSet results = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/account", "root", "mysql");
pstat = connection.prepareStatement("select * from account where money >?");
pstat.setObject(1,100);
results = pstat.executeQuery();
while (results.next()) {
// 获得每条数据,中name属性的值
System.out.println("name:"+results.getString("name"));
// 获得每条数据中,第1个属性的值(下标从1开始)
System.out.print("id值:"+results.getString(1));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
connection.close();
pstat.close();
results.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
oracle数据库
package com.example.demo.dao;
import java.sql.*;
public class StudentDaoImpl implements StudentDao {
public static final String URL = "jdbc:oracle:thin:@localhost:1521:orcl";
public static final String NAME = "scott";
public static final String PSW = "orcl";
public Connection connection;
public int add_dao() throws ClassNotFoundException {
Class.forName("oracle.jdbc.driver.OracleDriver");
try {
Connection conn =DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott", "orcl");
String sql ="insert into emp (empno) values(?)";
PreparedStatement pstat=conn.prepareStatement(sql);
pstat.setObject(1,200);
return pstat.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return 100;
}
}
更多推荐
已为社区贡献1条内容
所有评论(0)