PreparedStatement stm = c.prepareStatement("UPDATE user_table SET name=? WHERE id=?");
stm.setString(1, "the name");
stm.setInt(2, 345);
stm.executeUpdate();
public class TestQueries
{
public String getUsername(int id)
{
String username;
#sql
{
select username into :username
from users
where pkey = :id
};
return username;
}
}
You aren't creating SQL strings directly are you? That's the biggest no-no in programming. Please use PreparedStatements, and supply the data as parameters. It reduces the chance of SQL Injection vastly.
我一直在开发一个 Javaservlet 应用程序,该应用程序需要构造非常动态的 SQL 语句,以便进行即席报告。该应用程序的基本功能是将一组命名的 HTTP 请求参数提供给预编码的查询,并生成一个格式良好的输出表。我使用 Spring mVC 和依赖注入框架将所有 SQL 查询存储在 XML 文件中,并将它们连同表格格式信息一起加载到报告应用程序中。最终,报告需求变得比现有参数映射框架的功能更复杂,我不得不自己编写。这是一个有趣的开发实践,并且产生了一个参数映射框架,比我能找到的任何其他框架都更加健壮。
新的参数映射如下:
select app.name as "App",
${optional(" app.owner as "Owner", "):showOwner}
sv.name as "Server", sum(act.trans_ct) as "Trans"
from activity_records act, servers sv, applications app
where act.server_id = sv.id
and act.app_id = app.id
and sv.id = ${integer(0,50):serverId}
and app.id in ${integerList(50):appId}
group by app.name, ${optional(" app.owner, "):showOwner} sv.name
order by app.name, sv.name
select app.name as "App",
app.owner as "Owner",
sv.name as "Server", sum(act.trans_ct) as "Trans"
from activity_records act, servers sv, applications app
where act.server_id = sv.id
and act.app_id = app.id
and sv.id = 20
and app.id in (1,2,3,5,7,11,13)
group by app.name, app.owner, sv.name
order by app.name, sv.name
我真的认为 Spring 或 Hibernate 或者其中一个框架应该提供一个更健壮的映射机制来验证类型,允许复杂的数据类型,比如数组和其他类似的特性。我写我的引擎只是为了我的目的,它不是完全读一般发行。目前它只能处理 Oracle 查询,所有代码都属于一家大公司。有一天,我可能会采纳自己的想法,构建一个新的开源框架,但我希望现有的一个大玩家能够接受这个挑战。
You can also have a look at MyBatis (www.mybatis.org) . It helps you write SQL statements outside your java code and maps the sql results into your java objects among other things.
谷歌提供了一个名为 房间持续图书馆的库,它提供了一种非常简洁的方式来编写 SQL for Android Apps,基本上就是一个底层 SQLite 数据库的抽象层。Bellow 是官方网站上的一段简短代码:
@Dao
public interface UserDao {
@Query("SELECT * FROM user")
List<User> getAll();
@Query("SELECT * FROM user WHERE uid IN (:userIds)")
List<User> loadAllByIds(int[] userIds);
@Query("SELECT * FROM user WHERE first_name LIKE :first AND "
+ "last_name LIKE :last LIMIT 1")
User findByName(String first, String last);
@Insert
void insertAll(User... users);
@Delete
void delete(User user);
}