Searchcursor: How to add table from gdb to arcpy script? - arcpy

I have a gdb with a table that was generated from the Frequency tool and I want to add the table to the script. How can I access the table using a Search Cursor?
This is the script:
print "START"
arcpy.env.overwriteOutput = 1
fc = "D:\AVI \zl\zevel.gdb\point"
list_Fields = arcpy.ListFields(fc)
my_list = ("a","b","c")
for name in list_Fields:
if in my_list:
output = r"D:\AVI \zl\zevel.gdb"
tbl_name = output + r"\tbl"+"_"+
print tbl_name
### arcpy.SearchCursor....

I usually call cursor's using a with statement so I don't accidentally forget to close them and cause a data lock.
with arcpy.da.SearcCursor(fc, list_fields) as sr_cursor:
for row in sr_cursor:
# some code
sr_cursor = arcpy.da.SearchCursor(fc, list_fields)
for row in sr_cursor:
# some code
del sr_cursor # don't forget to delete the cursor if using this method
Hope this helps. For more info, check the arcgis resources page:


Dynamic variable parameter in static mysql query using groovy soap ui

I would like to generate the query that results for the BeneficiaryID 'ABC123' along with some other inputs if they were also given. Suppose if the currency value is given, I would like to include the Currency condition as well in the JOIN query, so as well the Category. I have the following code snippet in the SOAP UI Groovy script.
query= " CORR.BeneficiaryID LIKE 'ABC123'"
if (currencyValue!=""){
query=query + " and CORR.Currency LIKE '${currencyValue}'"
if (CategoryValue!=""){
query=query + " and CORR.Category LIKE '${CategoryValue}'"
}"Query" + query)
Outputrows = sql.rows("select CORR.Preferred as preferred ,CORR.Category as category,CORR.Currency as currency\
JOIN LOCATION LOC on CORR.UID=LOC.UID and ${query}"Output rows size" + Outputrows.size())
When currency and category are not given, I would like to have the following query run and get me the results.
select CORR.Preferred as preferred ,CORR.Category as category,CORR.Currency as currency\
and when the currency and category are given(say USD & Commercial), then the following query.
select CORR.Preferred as preferred ,CORR.Category as category,CORR.Currency as currency\
JOIN LOCATION LOC on CORR.UID=LOC.UID and CORR.BeneficiaryID LIKE 'ABC123' and CORR.Currency LIKE 'USD' and CORR.Category LIKE 'Commercial'
All I could see on the result for Outputrows.size() is zero(0).
Can you please correct me where am I doing wrong.
Here is changed script.
Since the issue to just build query, only putting that part remove sql execution part as that is not really the issue.
//Define the values or remove if you get those value from somewhere else
//Just put them here to demonstrate
//You may also try by empty value to make sure you are getting the right query
def currencyValue = 'USD'
def categoryValue = 'Commercial'
def query = 'select CORR.Preferred as preferred, CORR.Category as category,CORR.Currency as currency from BENEFICIARY CORR JOIN LOCATION LOC on CORR.UID = LOC.UID and CORR.BeneficiaryID LIKE \'ABC123\''
currencyValue ? (query += " and CORR.Currency LIKE '${currencyValue}'") : query
categoryValue ? (query += " and CORR.Category LIKE '${categoryValue}'") : query "Final query is \n ${query}"
You can just pass query to further where you need to run the sql, say sql.rows(query)
You may quickly try Demo

What is wrong with my sqlite3 CASE statement?

My code follows:
SELECT COUNT(_id) AS count FROM general WHERE _id = 1 CASE WHEN count > 0 THEN UPDATE general SET userGivenId = 'xxx' WHERE _id = 1 ELSE INSERT INTO general (userGivenId) VALUES ('xxx' ) END
With the error:
android.database.sqlite.SQLiteException: near "CASE": syntax error: , while compiling: SELECT COUNT(_id) AS count FROM general WHERE _id = 1 CASE WHEN count > 0 THEN UPDATE general SET userGivenId = 'xxx' WHERE _id = 1 ELSE INSERT INTO general (userGivenId) VALUES ('xxx' ) END
This is the shortest query I will use. Why I do this is because my other queries will have rows that needs to be updated but some may not be touched. Using replace will replace all the data (at least that is how it works for me on my Android phone). For instance my File class will have a filePath, but sometimes the response from the server will return null and I am only to update the File IF the server returns a new File.
Did I forget to write anything?
SQLite does not have any control logic because this would not make sense in an embedded database (there is no separate server machine/process whose asynchronous execution could improve performance).
CASE can be used only for expressions, not for entire commands.
Handle the control logic in your app:
Cursor c = db.rawQuery("SELECT 1 FROM general WHERE _id = 1", null);
if (c.moveToFirst())
db.execSQL("UPDATE general SET userGivenId = 'xxx' WHERE _id = 1");
db.execSQL("INSERT INTO general (userGivenId) VALUES ('xxx')");
For these particular commands, if you have a unique constraint on the _id column (and a primary key is constrained to be unique), you can use the INSERT OR REPLACE command:
INSERT OR REPLACE INTO general(_id, userGivenId) VALUES(1, 'xxx')

Migrate database with groovy script in grails

I have currently a database need to be migrated in grails. I have used
def sql =groovy.sql.Sql.newInstance(url,username,password,driver)
and after that I call
sql.eachRow("""select *\
from kontakt k join kommunikation c on k.kontakt_id = c.kontakt_id \
join kommunikationsmittel cm on c.kommittel_id = cm.kommittel_id \
join kommunikationstyp ct on c.komtyp_id = ct.komtyp_id \
join adresse a on a.Kontakt_ID = k.Kontakt_ID
""") {row->
The thing is that I can access the columnname via row.Strasse, row.PLZ and so on, but if there are two columns, which have the same name inside two different tables. How can I access different columns?
For example in 'Kommunikationsmittel' table there is a column 'Bezeichnung'. In 'Kommunikationstyp' there is also a column 'Bezeichnung'. How can I access via row?
Yeah, if you have duplicate field names, it's going to cause problems.
Your options are to either change the select so it is specific, and you can rename the conflicting fields, ie:
SELECT k.Strasse as kstrasse, a.Strasse AS astrasse FROM.....
Or, you can use the metaData for the row to get at all of the fields, as in this example:
sql.eachRow( '''...''' ) { row ->
row.getMetaData()*.columnName.eachWithIndex { name, index ->
println "$name = ${row[ index ]}"
By the way, you don't need \ chars in your SQL as you are using """, so lines will continue till the trailing """

The correct way to copy a field's data to another field in the same table with groovy

I'm writing my first groovy script to update the whole database table. Basically I want the number is the ID field to be put into ANOTHER_ID field
import groovy.sql.Sql
def url = project.getProperty("database.url")
def driver = project.getProperty("database.driver")
def user = project.getProperty("database.user")
def pass = project.getProperty("database.pass")
def output = properties['output']
def sql = Sql.newInstance(url, user, pass, driver)
def outwriter = new PrintWriter(output)
sql.eachRow("select * from THE_TABLE", { row ->
def id =
outwriter.println "Update THE_TABLE set (ANOTHER_ID)=(${id});"
} );
I'm posting to make sure I'm doing this correctly or if there is a better way of updating my table.
There's a problem with the SQL you're generating, it should be:
outwriter.println "UPDATE THE_TABLE SET ANOTHER_ID = ${} WHERE id = ${} ;"
However, you can replace this whole loop and everything with
outwriter.println "UPDATE THE_TABLE SET ANOTHER_ID = id ;"
Which will set every row in a single query instead of needing an UPDATE per row

Android sqlite delete row failure

I'm trying to delete a row in a table where I know the row exists. I tried:
final String s = "DELETE from %s where Name = '%s'";
String sql = String.format(s, GetTableName(), sListName);
Cursor cr= GetUserDb().GetSQLiteDb().rawQuery(sql, null);
and I tried:
String sWhere = String.format("Name = '%s'", sListName);
long lRowsUpdated = GetUserDb().GetSQLiteDb().delete(GetTableName(), sWhere, null);
** sWhere >> Name = 'groceries' **
** sql >> DELETE from Lists where Name = 'groceries' **
There is no crash or logcat exception but the row is still not deleted. Is there something I'm missing? Maybe I have a lock on it somewhere else or I need to set certain permissions in my Manifest or something?
Use delete() from SqliteDatabase - this returns the count of affected rows. E.g. delete(tablename, "name=?", new String[] { aString } )
Try this:
SQLiteStatement stmt = db.compileStatement("DELETE FROM " + getTableName() + "WHERE Name=?");
stmt.bindString(1, sListName);
if the column you're trying to have your key by is sListName you should have delete where sListName = '%s' unless you have another column that is called Name that you are trying to delete, but if that isn't your primary key you might end up getting two rows in your delete.
You can always use the emulator and an adb shell and just go run the sqlite3 shell command and try your SQL statements. If you type yours in and get 0 rows affected, you know you're statement is messed up, not your java.
If you're not using any built in CurorAdapters or ContentProviders your primary key does not need to be named _ID, it can be named whatever. As for the type, in SQLite3, it's really just a suggestion on how to cast it, you can put whatever data in whatever column you want.