1. 程式人生 > >java呼叫mysql資料庫的基本操作方法

java呼叫mysql資料庫的基本操作方法

一.  關於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資料庫的一些使用方法。