一. 关于java与mysql数据库的连接:
//加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");
//获取连接//http://baidu.com
Connection connection =DriverManager.getConnection("jdbc:mysql://localhost:3306/shopping?user=root&password=&char acterEncoding=utf-8");
//通过连接创建statement
Statement statement =connection.createStatement();
//定义sql
//执行sql语句,得到结果resultset
ResultSet rs=statement.executeQuery("select * from allshop where shopname='"+name+"'");
二. 关于mysql数据库的增删查改找
1.向数据库增加数据
try {//加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");
//获取连接//http://baidu.com
Connection connection =DriverManager.getConnection("jdbc:mysql://localhost:3306/shopping?user=root&password=&char acterEncoding=utf-8");
//通过连接创建statement
Statement statement =connection.createStatement();
String sql1 = "INSERT INTO buyer_order VALUES(NULL,'"+添加项+"','"+添加项+','"+添加项+"');";
//如果不添加数据则写为NULL
statement = connection.createStatement();
statement.execute(sql1);
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
2.删除数据库中的数据
try {
String sql = ("Delete from buyer_gouwuche where ids="+del+"");
statement.executeUpdate(sql);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
3.查询数据库中的数据
ResultSet rs=statement.executeQuery("select * from allshop where shopname='"+name+"'");
if(rs.next())
{System.out.println("记录存在");}
else
{System.out.println("记录不存在");}
4.修改数据库中的数据
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/shopping?user=root&password=&useUnicode=true&characterEncoding=utf-8");
PreparedStatement pst = connection.prepareStatement("update buyer_mytaobao set phonenumber=?,name=?,adress=? where phonenumber='"+phone+"'");
System.out.println(cm.getPhonenumber());
System.out.println(cm.getName());
System.out.println(cm.getAdress());
pst.setString(1, cm.getPhonenumber());
pst.setString(2, cm.getName());
pst.setString(3, cm.getAdress());
pst.executeUpdate();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
5.获取数据库中的数据
String sql = ("select * from allshop where ids='"+id+"' ");
System.out.println("new sql");
// 执行sql语句
ResultSet rs;
try {
rs = statement.executeQuery(sql);
if (rs.next()) {
// int id = rs.getInt("id");
String name = rs.getString("shopname");
float price = rs.getFloat("shopunitprice");
String image = rs.getString("image");
System.out.println(id);
System.out.println(name);
System.out.println(price);
System.out.println(image);
GoodsMessage g = new GoodsMessage(id, name, image, price);
return g;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
以上就是我所总结的关于java对mysql数据库的一些使用方法。