如何在Java程序中访问mysql数据库中的数据并进行简单的操作
展开全部
参考代码:
package 数据库编程;
import java.sql.*;
public class 数据库连接 {
public static void main(String[] args) throws SQLException{
//1.加载驱动程序
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//2.创建与DB数据库的连接
//连接字符串
String url="jdbc:mysql://192.168.1.101:3306/java数据库?user=root&password=humin";
Connection con=DriverManager.getConnection(url);
//进行读写
if(!con.isClosed()){
System.out.print("欢迎访问数据库!\n想做什么啊………………\n");
Statement st=con.createStatement();
ResultSet rs= st.executeQuery("select * from stu");
while(rs.next()){
System.out.print( rs.getString("stuid")+","+rs.getString("name")+","+rs.getString("sex")+","+rs.getString("age")+","+rs.getString("address")+","+rs.getString("tel")+"\n");
}
}
//关闭数据库
con.close();
}
}
package 数据库编程;
import java.sql.*;
public class 数据库连接 {
public static void main(String[] args) throws SQLException{
//1.加载驱动程序
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//2.创建与DB数据库的连接
//连接字符串
String url="jdbc:mysql://192.168.1.101:3306/java数据库?user=root&password=humin";
Connection con=DriverManager.getConnection(url);
//进行读写
if(!con.isClosed()){
System.out.print("欢迎访问数据库!\n想做什么啊………………\n");
Statement st=con.createStatement();
ResultSet rs= st.executeQuery("select * from stu");
while(rs.next()){
System.out.print( rs.getString("stuid")+","+rs.getString("name")+","+rs.getString("sex")+","+rs.getString("age")+","+rs.getString("address")+","+rs.getString("tel")+"\n");
}
}
//关闭数据库
con.close();
}
}
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询