下面的查询是为了在数据库中插入主数据:如果数据已经存在并且很好,我不想插入它并继续执行所有查询。
import groovy.sql.Sql
def props = [user: 'testing', password: 'testing', allowMultiQueries: 'true'] as Properties
def url = 'jdbc:mysql://161.91.235.239:3306/cf_85329a15_7ba0_44bb_a289_4ba9be98e661'
def driver = 'com.mysql.jdbc.Driver'
def sql = Sql.newInstance(url, props, driver)
sql.execute """
INSERT INTO `responses` (`ResponseID`,`RequestID`,`UnitSystemID`,`ResponseDateTime`,`UserID`,`UserSubscriptionID`,`ApplicationID`,`PropositionID`,`FeedDefinitionID`,`ObservationID`,`ResponseRAW`) VALUES (100000,0,1,'2015-01-13 07:48:00',1584,1,1,3,1,100008,'test');
INSERT INTO `responses` (`ResponseID`,`RequestID`,`UnitSystemID`,`ResponseDateTime`,`UserID`,`UserSubscriptionID`,`ApplicationID`,`PropositionID`,`FeedDefinitionID`,`ObservationID`,`ResponseRAW`) VALUES (100001,0,1,'2015-01-13 07:48:00',1584,1,1,3,1,500001,'test');
INSERT INTO `responses` (`ResponseID`,`RequestID`,`UnitSystemID`,`ResponseDateTime`,`UserID`,`UserSubscriptionID`,`ApplicationID`,`PropositionID`,`FeedDefinitionID`,`ObservationID`,`ResponseRAW`) VALUES (100002,0,1,'2015-01-13 07:48:00',1584,1,1,3,1,100007,'test');
答案 0 :(得分:0)
您可以在插入之前检查数据是否存在于表中。你应该这样做 的是:
import java.util.arrays
import groovy.sql.Sql
def props = [user: 'testing', password: 'testing', allowMultiQueries: 'true'] as Properties
def url = 'jdbc:mysql://161.91.235.239:3306/cf_85329a15_7ba0_44bb_a289_4ba9be98e661'
def driver = 'com.mysql.jdbc.Driver'
def sql = Sql.newInstance(url, props, driver)
def resulSelectValues = sql.execute "select distinct(`ResponseID`) from responses"
def tabQueryValues = {
{100000,0,1,'2015-01-13 07:48:00',1584,1,1,3,1,100008,'test'},
{100001,0,1,'2015-01-13 07:48:00',1584,1,1,3,1,500001,'test'},
{100002,0,1,'2015-01-13 07:48:00',1584,1,1,3,1,100007,'test'}
for (i=0;i<3;i++)
{
if(!Arrays.asList(resulSelectValues ).contains(tabQueryValues[i,0]))
{
sql.execute """
insert into responses`
(`ResponseID`,`RequestID`,`UnitSystemID`,`ResponseDateTime`,
`UserID`,`UserSubscriptionID`,`ApplicationID`,`PropositionID`,
`FeedDefinitionID`,`ObservationID`,`ResponseRAW`) values ("""
+tabQueryValues[i,0]+","+tabQueryValues[i,1]+","+tabQueryValues[i,2]
+","+tabQueryValues[i,3]+","+tabQueryValues[i,4]+
","+tabQueryValues[i,5]+","+tabQueryValues[i,6]+",
"+tabQueryValues[i,7]+","+tabQueryValues[i,8]+",
"+tabQueryValues[i,9]+","+tabQueryValues[i,10]);"
}
}
答案 1 :(得分:0)
您是否考虑过使用简单的try..catch?
try {
sql.execute """
} catch(SQLException ex) {
// data already exists, do nothing
}