java连接及操作mysql数据库
1.将mysql数据库驱动包导入项目里:
2代码:
`Connection con;//创建连接对象
String Driver="com.mysql.jdbc.driver";用于启动数据库驱动
String url="jdbc:mysql://localhost:12727/mvctest";//url
String user="root";//用户名
String password="123456"; //密码
//开始连接
try
{
Class.forName(Driver);//启动数据库驱动
con=DriverManager.getConnection(url,user,password);//用Driver的getConnection方法连接数据库
if(con.isclose())
{
System.out.println("数据库连接成功");
}
//操作数据库
//select语句用ResultSet resultset=stament.excuteQuery(),result接收的是一个结果集
//insert update delete用stament.excuteupdate(),返回的是数据库改变的行数
Stament stament=con.createStament();//创建stament对象,是sql语句的载体
String sql1="select * from user where id=1;";
String sql2="insert into user(usname,password,phone_number,address) values('hrl','123456','234567890','广东');";
ResultSet resultset=null//创建ResultSet对象
resultset=stament.excuteQuery(sql1);
stament.excuteupdate(sql2);
//操作完成
resultset.close();
stament.close();
con.close()
}
catch (ClassNotFoundException e) {
System.out.println("数据库驱动没有安装!");
e.printStackTrace();
} catch (SQLException e) {
System.out.println("数据库连接失败!");
e.printStackTrace();
}