参考代码:
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();
}
}