mysql简单数据库连接

package connect;

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

public class Connect {
public static void main(String[] args) {
try {
Class.forName(“com.mysql.jdbc.Driver”);
String url=”jdbc:mysql://localhost:3306/kaoshi”;//kaoshi是自己的数据库
Connection conn=DriverManager.getConnection(url, “root”, “admin”);//自己的用户名和密码
System.out.println(“数据库连接成功”);
Statement stm=conn.createStatement();
String sql=”select * from tab_student”;
ResultSet rs=stm.executeQuery(sql);
while(rs.next()){
System.out.println(“姓名:”+rs.getString(“stu_name”)+” 年龄:”+rs.getInt(“stu_age”));
rs.close;
stmt.close();
conn.close();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally{
try {
if (stmt!=null) stmt.close();
} catch (SQLException se2) {
}
try {
if (conn!=null) conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
System.out.println(“拜拜!”);
}

}

猜你喜欢

转载自blog.csdn.net/baidu_38919965/article/details/81805189