JAVA 连接 mysql 数据库
通常在程序中进行增删改查时,连接并对数据库进行操作的步骤为:
1、建立数据源
2、导入用到的包
3、加载驱动程序
4、创建与数据库的连接
5、创建语句对象
6、编写具体的SQL语句
7、执行具体的SQL语句
8、处理数据
9、关闭对象
10、处理异常
下面看一个简单的例子
public void select()
{
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
String user = "root" ;//用户名是root
String password = "root";//密码是root
String driverName = "com.mysql.jdbc.Driver";
String conStr = "jdbc:mysql://localhost:3306/db";//db是数据库的名字
try{
Class.forName(driverName);
con = DriverManager.getConnection(conStr,user,password);
stmt = con.createStatement();
String sql = "select * from table";
rs = stmt.executeQuery(sql);
while(rs.next())
{
System.out.println(rs.getString(1));
}
}catch()
{}
finally
{
if(rs!=null){
rs.close();
stmt.close();
con.close();
}
}