1. 程式人生 > >java常用程式碼塊整理

java常用程式碼塊整理

1.資料庫操作(查詢、更新等)

nameGet='%'+nameGet+'%';
String sqlGname = "SELECT * FROM GOODS WHERE GNAME LIKE ?";
try
{
	pstmt = conn.prepareStatement(sqlGname);
	pstmt.setString(1, nameGet);
	rs = pstmt.executeQuery();
	while (rs.next())
	{
	    int gid = rs.getInt("gid");
		String gname = rs.getString(2);
		double gprice = rs.getDouble(3);
		int gnum = rs.getInt(4);
		Goods goods = new Goods(gid,gname,gprice,gnum);
		goodsList.add(goods);
		}
	} catch (SQLException e)
	{
		e.printStackTrace();
	}finally
	{
		DbClose.queryClose(pstmt, rs, conn);
	}

2、連線資料庫

public final class DbConn
{
	public static  Connection getconn()
	{
		Connection conn = null;
		
		String user   = "root";
		String passwd = "root";
		String url = "jdbc:mysql://localhost:3306/shop";
		
		//已載入完驅動
		try
		{
			Class.forName("com.mysql.jdbc.Driver"); 
			conn = DriverManager.getConnection(url,user,passwd);
		}catch (SQLException e)
		{
			e.printStackTrace();
		}
		catch (ClassNotFoundException e)
		{
			e.printStackTrace();
		}
		return conn;
	}

}