这两个语句有什么区别,它们的工作方式相同,还是第一个完全有效?我可以在“插入到”之后使用变量吗?
stmt = conn.prepareStatement("INSERT INTO treatment(CPR,Treatment,ID,TreatedOn) "+
"VALUES("+Cpr+Id+date.toString());
id
, cpr
是 string
, int
或其他变量,bin 我的情况是字符串
,
PreparedStatement insertStatement;
insertStatement = connection.prepareStatement("INSERT INTO sep2.movies(title,length) "
+ "VALUES (?,?,?)");
insertStatement.setString(1, Title);
insertStatement.setInt(2, movie.getLength());
其中 Title
是一个字符串,getLength
返回一个 int
。
我应该使用其中的哪一个?
我明白 setString
的作用,但我必须使用它吗?
此外,我仅将基本/非对象数据类型插入到 Treatment
中。这有什么不同吗? (如果重要的话,我正在使用 postgres)
最佳答案
使用绑定(bind)变量的另一个重要方面是它提高了应用程序的性能。当您使用绑定(bind)变量时,数据库服务器缓存和优化查询并提高应用程序的性能(在时间和处理方面)。
例如, 当你使用
insertStatement = connection.prepareStatement("INSERT INTO sep2.movies(title,length) "
+ "VALUES (?,?,?)");
insertStatement.setString(1, Title);
insertStatement.setInt(2, movie.getLength());
该语句在数据库服务器中兑现,只有参数在数据库中的运行时绑定(bind)。这将显着提高性能。
您可以阅读 为性能和可伸缩性设计应用程序 Oracle 白皮书 http://www.oracle.com/technetwork/database/performance/designing-applications-for-performa-131870.pdf
关于Java-to-sql语句,Insert into vs setString中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51841526/