i want to Getting JSON values in python - sql-server

Sorry. I can not explain the details because I am not fluent in English.
I have a json document like this:
[
{
"id":"96103252",
"pvname":"Bet365",
}
]
My python code looks like this:
url_odds= cfg.oddsurl
oddsfeed = urllib2.urlopen(url_odds)
oddsjson = json.load(oddsfeed)
getjson = "{""data"":" + oddsjson + "}"
for sport in getjson["data"]:
pv_id= validate(sport,"id")
pv_name= validate(sport,"pv_name")
sql= "INSERT INTO odds_sports(pv_id,pv_name) VALUES ('"
sql= sql+ pv_id + "','"
sql= sql+ pv_name + "')"
cursor.execute(sql)
conn.commit()
It sends this error
getjson = "{""data"":" + oddsjson + "}"
TypeError: cannot concatenate 'str' and 'list' objects

that's a very simple syntax error. in this line:
getjson = "{""data"":" + oddsjson + "}"
oddsjson is an array of dicts, you probably want to iterate over each element in it and parse the right value hence:
for sport in oddsjson:
pv_id = validate(sport.get("id"))
pv_name = validate(sport.get("pvname"))
also,
and on another issue. hand-writing SQL queries with strings you generate on the go is an invitation for troubles (especially when the query involves dynamic string generated by others).
you better use some library like sqlalchemy as a middleware to your database.

Related

TypeError: validate() takes exactly 2 arguments (1 given)

I tried several times, but I can not resolve the error.
My python code looks like this:
def validate(item,key):
if key in item:
if isinstance( item[key], ( int, long, float) ):
stro=str(item[key])
if stro.lower()=="true":
return "1"
if stro.lower()=="false":
return "0"
return str(item[key])
stro= item[key].encode('ascii', 'replace')
return stro.replace("'","''")
else:
return "null"
for sport in oddsjson:
pv_id = validate(sport.get("id"))
pv_name= validate(sport,get("name"))
sql= "INSERT INTO odds_sports(pv_id,pv_name) VALUES ('"
sql= sql+ pv_id + "','"
sql= sql+ pv_name + "')"
cursor.execute(sql)
conn.commit()
It sends this error
pv_id = validate(sport.get("id"))
TypeError: validate() takes exactly 2 arguments (1 given)
This error is as straightforward as it gets.
def validate(item, key)
validate expects 2 arguments: item and key.
However, you only provide one:
pv_id = validate(sport.get("id"))
Bonus points:
You have a typo on the next line:
pv_name = validate(sport,get("name"))
# ^ comma
should be
pv_name = validate(sport.get("name"))
# ^ dot
Your code is vulnerable to SQL injection. Use a parameterized query instead of concatenating queries.
sql = "INSERT INTO odds_sports(pv_id, pv_name) VALUES (?, ?)" # or %s, depending on
# the library/connector
# you are using
cursor.execute(sql, (pv_id, pv_name))

Maximum number of inserts per transaction on SQL Server

Does anyone know how many INSERT commands per transaction SQL Server can handle at the same time? Basically, I'm building a long string with bunch of INSERT's (around 8000 INSERT commands, and each has around 600 characters) which then I will execute using a function SQLexcute(sql_text):
for(obj in objects) {
sql_text += "INSERT(prop1, prop2, prop3, prop4, prop5) VALUES(" + obj.prop1 + "," + obj.prop2 + "," + obj.prop3 + "," + obj.prop4 + "," + obj.prop5+");"
}
SQLexcute(sql_text)
Sean is right.
Do not execute the code in mosel. You have to create your query in T-SQL and pass the parameters there.
Here you have the link for table valued param:
Tabled valued param

Multiple tag search engine

Whenever we use hashtag for searching that always results from a single tag (except Tumblr).
Just wondering is there a search engine allows multiple tag search?
I suppose that using different combination of tags could be fun and accurate:
#A general results
#A, #B more specific
#A, #B, #C, #D close to the truth what attributes (tags) are given.
Is any website served in this way?
Or how can I build a database to make this happened?
Thank you a lot.
This is old and written in VB but the principle I think will work for you.
This code is not completely limiting to Images that have all of the tags it is instead pushing the images with the most tag hits to the top.
This code works from the idea of show the user what fits best first but then give them other options below. Where as your AND scenario would cut out something that worked for 4 out of 5 of the tags. In this scenario they would just show below tags that had 5 out of 5.
So if you had some images with tags like:
Given:
Image1 woman,dog,panda
Image2 woman,telephone,smiling
Image3 man,dog,panda,banana
Image4 man,telephone,smiling
Yield:
A tag search of "telephone smiling" would score [Image2] and [Image4] to the top of the listing.
A tag search of "panda" would only yield Image1 and Image3.
A tag search of "man dog panda banana" Would yield Image3 as the top followed by Image1 followed by Image4.
This implementation is for finding the best image based on tags.
You create 3 tables in your SQL database as such (if you are doing webpages or stories or whatever change image to that for your own clarity):
SQL Tables:
imageTag [INT ID, String Tag]
imageImages [INT ID, NVARCHAR(2000) Path]
imageConnections [INT TagID, INT ImageID]
VB.NET Code:
'The beef of the SQL statement to get the scored results is here.
Dim SearchString As String =
"SELECT it.path, count(it.path) AS cnt, it.Id, it.name, it.description, it.updated FROM imageimages AS it, imageconnections AS itt, imagetags AS t WHERE " + _
"{REPLACE-TAG} AND t.id = itt.tagid AND it.id = itt.imageid " + _
"GROUP BY Path, it.ID, it.name, it.description, it.updated ORDER BY cnt DESC"
Dim keywords As String() = tstSearch.Text.Split(New String() {" "}, StringSplitOptions.RemoveEmptyEntries)
If keywords.Length > 0 Then
Dim strReplacement As String
strReplacement = "( tag = '" + keywords(0) + "'"
If keywords.Length > 1 Then
For i As Integer = 1 To keywords.Length - 1
strReplacement += " OR tag = '" + keywords(i) + "'"
Next
End If
strReplacement += " )"
SearchString = SearchString.Replace("{REPLACE-TAG}", strReplacement)
dt = tran.GetDataTable(SearchString)
End If

How to set two FilterString condtion on code Reports Winforms Devexpress?

am using devexpress winforms reports, I can able to set one filterString condition in code, this code is working successful
report.FilterString = "CompanyId =" + compid;
and
DetailReport.FilterString = "CompanyId=" + compid;
But now I need to set for two conditions I tried this code but it didn't filter display all
values.
report.FilterString = "[CompanyId = " + compid +"] AND [ InvoiceStatus =" + status + "]";
Help me how to solve this ?
The simplest filter syntax looks like this: "[FieldName] = Value".
Thus, change your code as follows:
report.FilterString = string.Format("[CompanyId] = {0} AND [InvoiceStatus] = {1}", compid, status);
Thanks to all. Finally solved by this code and working fine for two filters using correct string formats.
report.FilterString = "InvoiceStatus = '" + status + "' AND CompanyId = " + compid;

How can I add more than 1 filter to persistence manager query in Java Google App Engine?

I'm using Java servlets to develop a Google App Engine application. I need to write up a query with more than 1 condition in the where clause. The commented out line below gives me query_parsing error. Is there a way to add more than one condition in the where clause?
String query = "select from " + Human.class.getName();
query += " where name == '" + request.getParameter("name") + "'";
//query += " and lastname == '" + request.getParameter("lastname") + "'";
List<Human> humans = (List<Human>) pm.newQuery(query).execute();
I know this is possible with JDO queries such as the below. However, my version is different. I'm using a String object to write up the query and then execute it with persistence manager (Please see above).
Query query = pm.newQuery(Employee.class);
query.setFilter("lastName == lastNameParam");
query.setOrdering("hireDate desc");
query.declareParameters("String lastNameParam");
In your first code snippet, I believe the issue is the word 'and', which should be '&&'. To have multiple filters, as in your second snippet, you would also use the '&&' operator.
String query = "select from " + Human.class.getName();
query += " where name == '" + request.getParameter("name") + "'";
query += " && lastname == '" + request.getParameter("lastname") + "'";
List<Human> humans = (List<Human>) pm.newQuery(query).execute();
or
Query query = pm.newQuery(Employee.class);
query.setFilter("lastName == lastNameParam && name == nameParam");
query.setOrdering("hireDate desc");
query.declareParameters("String lastNameParam");
query.declareParameters("String nameParam");

Resources