当前位置:Gxlcms > 数据库问题 > 如何使用纯Java方式连接数据库?

如何使用纯Java方式连接数据库?

时间:2021-07-01 10:21:17 帮助过:17人阅读


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

/**
* jdbc程序
* @author Administrator
*
*/
public class JdbcDemo01 {
public static void main(String[] args) throws Exception {
//1.加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");
//2.与数据库连接
Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/myschool", "root", "0000");
//测试连接
System.out.println(connection);
//3.创建执行sql语句的对象
Statement stmt = connection.createStatement();
//4.执行sql语句获取结果集
ResultSet rs = stmt.executeQuery("select * from subject");
//5.遍历结果集获取数据
while(rs.next()){
int subjectNo = rs.getInt("SubjectNo");
String SubjectName = rs.getString("SubjectName");
int classHour = rs.getInt("ClassHour");
int gradeID = rs.getInt("GradeID");

System.out.println(subjectNo+"\t"+SubjectName+"\t"+classHour+"\t"+gradeID);
}
//6.释放资源
rs.close();
stmt.close();
connection.close();
}
}

2.使用纯Java方式连接数据库实现增删改操作(增删改操作都使用executeUpdate方法)

package cn.bdqn.demo;

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

//JDBC实现添加
public class JdbcDemo3 {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/myschool", "root", "0000");
stmt = conn.createStatement();
int i = stmt.executeUpdate("INSERT INTO `subject`(SubjectName,ClassHour,GradeID) VALUES (‘历史‘,101,1)");
if (i > 0){
System.out.println("添加成功!");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 释放资源
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
stmt = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
}
}

 

 

如何使用纯Java方式连接数据库?

标签:while   语句   connect   cal   ccf   dem   []   root   res   

人气教程排行