package testJDBC; import java.sql.*; public class JDBCdemo1 { public static void main(String[] args){Co
package testJDBC;
import java.sql.*;
public class JDBCdemo1 {
public static void main(String[] args){
Connection conn = null;
Statement statement = null;
ResultSet resultSet = null;
//1.注册数据库驱动
try {
Class.forName("com.Mysql.jdbc.Driver");
//加载一个类到内存中,该类中有一静态代码块,该代码块中有注册驱动的代码
//静态代码块伪代码如下:DriverManager.reGISterDriver( new Driver() )
//2.获取数据库连接
String url = "jdbc:mysql://localhost:3306/" +
"jt_db" +
"?characterEncoding=utf-8";
String user = "root"; //数据库连接用户名
String passWord = "123456"; //数据库连接密码
conn = DriverManager.getConnection(url, user, passWord);
//3.获取传输器
statement = conn.createStatement();
//4.执行sql语句,返回执行结果
String sql = "select * from account";
resultSet = statement.executeQuery(sql);
//5.处理结果
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
double money = resultSet.getDouble("money");
System.out.println(id + ":" + name + ":" + money);
}
}catch (Exception e){
e.printStackTrace();
}finally {
//6.释放资源
//越晚获取越先释放!!
//最好将释放资源代码放在finally里
if(resultSet!=null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
resultSet = null;
}
}
if(statement!=null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
statement = null;
}
}
if(conn!=null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
conn = null;
}
}
}
}
}
--结束END--
本文标题: JDBC连接MySQL操作步骤
本文链接: https://lsjlt.com/news/50171.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-10-23
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0