-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.html
More file actions
440 lines (383 loc) · 23.8 KB
/
index.html
File metadata and controls
440 lines (383 loc) · 23.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
<!DOCTYPE html>
<html lang="en">
<head prefix="og: http://ogp.me/ns# article: http://ogp.me/ns/article#">
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width">
<title>Heuristic Intelligence</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.4.1/css/bulma.min.css">
<link rel="stylesheet" href="/theme/css/main.365169ea.css">
<link rel="stylesheet" href="/theme/webassets-external/5f88595a9ad2c678b16c0d171e6e0a71_print.css" media="print">
</head>
<body id="index" class="home">
<header class="hero is-primary">
<div class="hero-head">
<div class="container">
<nav class="nav">
<div class="nav-left">
<a class="nav-item is-brand title is-3 is-active"
href="/">Heuristic Intelligence</a>
</div>
</nav>
</div>
</div>
</header>
<nav class="nav has-shadow is-hidden-print">
<div class="container">
<div class="nav-center"></div>
<span id="navToggle" class="nav-toggle">
<span></span>
<span></span>
<span></span>
</span>
<div id="navMenu" class="nav-right nav-menu">
<a class="nav-item is-tab "
href="/category/graphlab.html">GraphLab</a>
<a class="nav-item is-tab "
href="/category/machine-learning.html">Machine Learning</a>
<a class="nav-item is-tab "
href="/category/misc.html">Misc</a>
<a class="nav-item is-tab "
href="/category/python.html">Python</a>
<a class="nav-item is-tab "
href="/category/statistics.html">Statistics</a>
</div>
</div>
</nav>
<div class="container">
<div class="section columns">
<div class="column is-three-quarters-desktop is-two-thirds-tablet">
<aside id="featured" class="body">
<article>
<h1 class="title">
<a href="/2017/Sep/20/psycopg_postgresql_adapter_for_python.html">Psycopg: PostgreSQL adapter for Python</a>
</h1>
<footer class="post-info">
<abbr class="published" title="2017-09-20T00:08:00+05:30">
Published <span class="is-info">Wed 20 September 2017</span>
in <a href="/category/python.html">Python</a>
</abbr>
<p class="author">
<em>by Prashant Gonarkar
</em>
<span class="tag is-small"><a href="/tag/python.html">python</a></span>
<span class="tag is-small"><a href="/tag/postgres.html">postgres</a></span>
</p>
</footer> <div class="section">
<!-- <p><a href="https://www.postgresql.org/">PostgreSQL</a> is one the most popular open source object-relational database system & heavily being used in industry. On the other hand python is widely used multiple programming paradigm language. If you want to work in PostgreSQL using python, the best choice would be Psycopg. <a href="http://initd.org/psycopg/">Psycopg</a> is the most popular PostgreSQL adapter for python. It fully implements <a href="www.python.org/dev/peps/pep-0249/">Python DB API 2.0</a>. Psycopg2 is designed for multi-threaded applications and maintaines its own connection pool. <br/> One of nice feature that psycopg2 driver supports, it matches Python objects to the PostgreSQL data types e.g list to the array, tuples to records, and dictionary to hstore.
The following tutorials will demonstrate basic usage of psycopg.</p>
<div class="highlight"><pre><span></span><span class="c1"># Python 3.5</span>
<span class="c1"># Connecting to PostgreSQL database from python </span>
<span class="c1"># importing psycopg2 module</span>
<span class="kn">import</span> <span class="nn">psycopg2</span>
<span class="k">try</span><span class="p">:</span>
<span class="n">conn</span> <span class="o">=</span> <span class="n">psycopg2</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="s2">"dbname='tempdb' user='postgres' host='localhost' password='postgres'"</span><span class="p">)</span>
<span class="k">except</span> <span class="ne">Exception</span> <span class="k">as</span> <span class="n">ex</span><span class="p">:</span>
<span class="k">print</span><span class="p">(</span><span class="s2">"Error: unable to connect to the database"</span><span class="p">,</span><span class="n">ex</span> <span class="p">)</span>
</pre></div>
<div class="highlight"><pre><span></span><span class="c1"># we got connection </span>
<span class="n">conn</span>
</pre></div>
<div class="highlight"><pre><span></span><connection object at 0x7f93202a5e88; dsn: 'user=postgres host=localhost dbname=tempdb password=xxx', closed: 0>
</pre></div>
<p>After connecting to database, we need to create cursor by the connection.cursor() method. And they are bound to the connection for the entire lifetime.</p>
<div class="highlight"><pre><span></span><span class="c1"># Creating cursor</span>
<span class="n">cur</span> <span class="o">=</span> <span class="n">conn</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>
</pre></div>
<p>Now after having the cursor defined we can execute a query by cursor.execute() function. </p>
<div class="highlight"><pre><span></span><span class="c1"># Let's fetch 5 rows from test table</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">"SELECT * FROM test LIMIT 5;"</span><span class="p">)</span>
</pre></div>
<p>To get the results returned by query there are multiple functions available in psycopg2 based on return values e.g fetchall()(), fetchone() & fetchmany() </p>
<div class="highlight"><pre><span></span><span class="c1"># Let's get all the data retrieved by query</span>
<span class="n">cur</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()</span>
</pre></div>
<div class="highlight"><pre><span></span>[(1, 122, 5.0), (1, 185, 5.0), (1, 231, 5.0), (1, 292, 5.0), (1, 316, 5.0)]
</pre></div>
<p>As you can see above psycopg2 automatically converts data into python built-in list.</p>
<p>Now Let's create a new table in given database.</p>
<div class="highlight"><pre><span></span><span class="c1"># Creating new table using SQL query</span>
<span class="n">tablename</span> <span class="o">=</span> <span class="s2">"ratings"</span>
<span class="n">USER_ID_COLNAME</span> <span class="o">=</span> <span class="s1">'userId'</span>
<span class="n">MOVIE_ID_COLNAME</span> <span class="o">=</span> <span class="s1">'movieId'</span>
<span class="n">RATING_COLNAME</span> <span class="o">=</span> <span class="s1">'rating'</span>
<span class="k">try</span><span class="p">:</span>
<span class="n">query</span> <span class="o">=</span> <span class="s2">"CREATE TABLE {0} ( {1} integer, {2} integer,{3} real);"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">tablename</span><span class="p">,</span>
<span class="n">USER_ID_COLNAME</span><span class="p">,</span>
<span class="n">MOVIE_ID_COLNAME</span><span class="p">,</span>
<span class="n">RATING_COLNAME</span><span class="p">)</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">query</span><span class="p">)</span>
<span class="k">except</span> <span class="ne">Exception</span> <span class="k">as</span> <span class="n">ex</span><span class="p">:</span>
<span class="k">print</span><span class="p">(</span><span class="s2">"Failed to create table: "</span><span class="p">,</span><span class="n">ex</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="s2">"Created table: "</span><span class="p">,</span> <span class="n">tablename</span><span class="p">)</span>
</pre></div>
<div class="highlight"><pre><span></span>Created table: ratings
</pre></div>
<p>Table created sucessfully .! Now let's add some data. psycopg2 supports PostgreSQL's COPY command.</p>
<div class="highlight"><pre><span></span><span class="c1"># Adding data from csv file using COPY method of PostgreSQL</span>
<span class="c1"># datafile is sample.csv</span>
<span class="n">tablename</span> <span class="o">=</span> <span class="s2">"ratings"</span>
<span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">'sample.csv'</span><span class="p">)</span> <span class="k">as</span> <span class="n">datafile</span><span class="p">:</span>
<span class="k">try</span><span class="p">:</span>
<span class="n">cur</span><span class="o">.</span><span class="n">copy_from</span><span class="p">(</span><span class="n">datafile</span><span class="p">,</span><span class="n">tablename</span> <span class="p">)</span>
<span class="n">conn</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>
<span class="k">except</span> <span class="ne">Exception</span> <span class="k">as</span> <span class="n">ex</span><span class="p">:</span>
<span class="k">print</span><span class="p">(</span><span class="s2">"Failed to copy file in database: "</span><span class="p">,</span><span class="n">ex</span><span class="p">)</span>
</pre></div>
<p>Now let's fetch added data</p>
<div class="highlight"><pre><span></span><span class="c1"># Running select query and feching data </span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">"SELECT * FROM ratings LIMIT 5;"</span><span class="p">)</span>
<span class="n">rows</span> <span class="o">=</span> <span class="n">cur</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()</span>
<span class="n">rows</span>
</pre></div>
<div class="highlight"><pre><span></span>[(1, 122, 5.0), (1, 185, 5.0), (1, 231, 5.0), (1, 292, 5.0), (1, 316, 5.0)]
</pre></div>
<p>Let's count the the number of rows in table. Here we will use fetchone()</p>
<div class="highlight"><pre><span></span><span class="c1"># count the number of rows</span>
<span class="n">tablename</span> <span class="o">=</span> <span class="s2">"ratings"</span>
<span class="n">query</span> <span class="o">=</span> <span class="s2">"SELECT count(*) FROM {0}"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">tablename</span><span class="p">)</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">query</span><span class="p">)</span>
<span class="n">count</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">cur</span><span class="o">.</span><span class="n">fetchone</span><span class="p">()[</span><span class="mi">0</span><span class="p">])</span>
<span class="n">count</span>
</pre></div>
<div class="highlight"><pre><span></span>400
</pre></div>
<p>Similarly let's count number of tables</p>
<div class="highlight"><pre><span></span><span class="c1"># counting no of tables in schema</span>
<span class="n">query</span> <span class="o">=</span> <span class="s2">" SELECT COUNT(table_name) FROM information_schema.tables WHERE table_schema = 'public' "</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">query</span><span class="p">)</span>
<span class="n">count</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">cur</span><span class="o">.</span><span class="n">fetchone</span><span class="p">()[</span><span class="mi">0</span><span class="p">])</span>
<span class="n">count</span>
</pre></div>
<div class="highlight"><pre><span></span>4
</pre></div>
<p>Let's delete perticular table.</p>
<div class="highlight"><pre><span></span><span class="c1"># deleting ratings table </span>
<span class="n">RATINGS_TABLE</span> <span class="o">=</span> <span class="s1">'ratings'</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s1">'DROP TABLE IF EXISTS {0} CASCADE'</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">RATINGS_TABLE</span><span class="p">))</span>
<span class="n">cur</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>
</pre></div>
<p>PostgreSQL does not have an autocommit option which means all the queries will have to be executed within a transaction. This functionality ensures data integrity and allows for appropriate error handling but there are queries that can not be run from within a transaction. Let's see example.</p>
<div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">"DROP DATABASE tempd"</span><span class="p">)</span>
<span class="k">except</span> <span class="ne">Exception</span> <span class="k">as</span> <span class="n">ex</span><span class="p">:</span>
<span class="k">print</span><span class="p">(</span><span class="s2">"Failed to drop our test database!"</span><span class="p">,</span><span class="n">ex</span><span class="p">)</span>
</pre></div>
<div class="highlight"><pre><span></span>Failed to drop our test database! DROP DATABASE cannot run inside a transaction block
</pre></div>
<p>PostgreSQL can not drop databases within a transaction, if you want to drop database within a transaction then you need to change the isolation level of the database as follows.</p>
<div class="highlight"><pre><span></span><span class="n">conn</span><span class="o">.</span><span class="n">set_isolation_level</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
</pre></div>
<p>This was short introduction to psycopg, I hope you have enjoyed. See you next time.</p>
<h2>References</h2>
<ol>
<li><a href="http://initd.org/psycopg/">Psycopg official website</a></li>
<li><a href="https://wiki.postgresql.org/wiki/Psycopg2_Tutorial">PostgreSQL psycopg2 tutorial</a></li>
</ol>-->
<p>Getting started with PostgreSQL in python using psycopg</p>
<a href="/2017/Sep/20/psycopg_postgresql_adapter_for_python.html">Read more...</a>
<p><a href="/2017/Sep/20/psycopg_postgresql_adapter_for_python.html#disqus_thread"></a></p> </div>
</article>
</aside>
<div class="is-hidden-print">
<h2 class="subtitle">Other articles</h2>
<div class="columns is-multiline">
<div class="column is-half-tablet is-one-third-desktop">
<div class="card is-fullwidth is-fullheight">
<div class="card-content">
<a href="/2017/Jul/12/introduction_to_pandas_toolkit.html">
<h3 class="title is-5">Introduction to Pandas Toolkit</h3>
<div class="heading subtitle">Wed 12 July 2017</div>
<div><p>Introduction to Pandas Toolkit</p></div>
</a>
<p><a href="/2017/Jul/12/introduction_to_pandas_toolkit.html#disqus_thread"></a></p> </div>
</div>
</div>
<div class="column is-half-tablet is-one-third-desktop">
<div class="card is-fullwidth is-fullheight">
<div class="card-content">
<a href="/2017/Jul/09/probablity_distributions.html">
<h3 class="title is-5">Probablity Distributions</h3>
<div class="heading subtitle">Sun 09 July 2017</div>
<div><p>Probablity Distributions from programmer's perspective</p></div>
</a>
<p><a href="/2017/Jul/09/probablity_distributions.html#disqus_thread"></a></p> </div>
</div>
</div>
<div class="column is-half-tablet is-one-third-desktop">
<div class="card is-fullwidth is-fullheight">
<div class="card-content">
<a href="/2017/Jan/04/Introduction-to-python-programming-and-numpy.html">
<h3 class="title is-5">Introduction to Python Programming and Numpy</h3>
<div class="heading subtitle">Wed 04 January 2017</div>
<div><p>Introduction to Python Programming and Numpy</p></div>
</a>
<p><a href="/2017/Jan/04/Introduction-to-python-programming-and-numpy.html#disqus_thread"></a></p> </div>
</div>
</div>
<div class="column is-half-tablet is-one-third-desktop">
<div class="card is-fullwidth is-fullheight">
<div class="card-content">
<a href="/2016/Jul/03/welcome.html">
<h3 class="title is-5">Welcome</h3>
<div class="heading subtitle">Sun 03 July 2016</div>
<div><p>Welcome to Data Science blog !</p></div>
</a>
<p><a href="/2016/Jul/03/welcome.html#disqus_thread"></a></p> </div>
</div>
</div>
<div class="column is-half-tablet is-one-third-desktop">
<div class="card is-fullwidth is-fullheight">
<div class="card-content">
<a href="/2016/Mar/13/deep_learning_image_classification.html">
<h3 class="title is-5">Deep Learning Image Classification</h3>
<div class="heading subtitle">Sun 13 March 2016</div>
<div><p>Deep Learning Image Classification</p></div>
</a>
<p><a href="/2016/Mar/13/deep_learning_image_classification.html#disqus_thread"></a></p> </div>
</div>
</div>
<div class="column is-half-tablet is-one-third-desktop">
<div class="card is-fullwidth is-fullheight">
<div class="card-content">
<a href="/2016/Mar/12/image_retrieval_using_deep_features.html">
<h3 class="title is-5">Image Retrieval using Deep Features</h3>
<div class="heading subtitle">Sat 12 March 2016</div>
<div><p>Image Retrieval using Deep Features</p></div>
</a>
<p><a href="/2016/Mar/12/image_retrieval_using_deep_features.html#disqus_thread"></a></p> </div>
</div>
</div>
<div class="column is-half-tablet is-one-third-desktop">
<div class="card is-fullwidth is-fullheight">
<div class="card-content">
<a href="/2016/Mar/06/song_recommendation_system.html">
<h3 class="title is-5">Song Recommendation System</h3>
<div class="heading subtitle">Sun 06 March 2016</div>
<div><p>In this article we focused on building recommender systems to find products, music and movies that interest ...<br /></p></div>
</a>
<p><a href="/2016/Mar/06/song_recommendation_system.html#disqus_thread"></a></p> </div>
</div>
</div>
<div class="column is-half-tablet is-one-third-desktop">
<div class="card is-fullwidth is-fullheight">
<div class="card-content">
<a href="/2016/Feb/28/clustering_and_similarity_of_wikipedia_articles.html">
<h3 class="title is-5">Clustering and Similarity of Wikipedia Articles</h3>
<div class="heading subtitle">Sun 28 February 2016</div>
<div><p>Clustering and Similarity of Wikipedia Articles</p></div>
</a>
<p><a href="/2016/Feb/28/clustering_and_similarity_of_wikipedia_articles.html#disqus_thread"></a></p> </div>
</div>
</div>
<div class="column is-half-tablet is-one-third-desktop">
<div class="card is-fullwidth is-fullheight">
<div class="card-content">
<a href="/2016/Feb/21/analyzing_amazon_product_sentiment.html">
<h3 class="title is-5">Analyzing Amazon Product Sentiment</h3>
<div class="heading subtitle">Sun 21 February 2016</div>
<div><p>Analyzing Amazon Product Sentiment</p></div>
</a>
<p><a href="/2016/Feb/21/analyzing_amazon_product_sentiment.html#disqus_thread"></a></p> </div>
</div>
</div>
</div>
<nav class="pagination is-centered">
<a class="pagination-previous" href="#" disabled>
Previous
</a>
<a class="pagination-next"
href="/index2.html">
Next page
</a>
<ul class="pagination-list">
<li>Page 1 / 2</li>
</ul>
</nav>
<br> </div>
</div>
<div class="column is-one-quarter-desktop is-one-third-tablet is-hidden-print">
<aside class="menu">
<p class="menu-label">Links</p>
<ul class="menu-list">
<li><a href="/pages/about.html">
<span class="icon is-small"><i class="fa fa-book"></i></span>
<span class="link-text">About</span>
</a></li>
<li><a href="/pages/projects.html">
<span class="icon is-small"><i class="fa fa-book"></i></span>
<span class="link-text">Projects</span>
</a></li>
</ul>
<p class="menu-label">Social</p>
<ul class="menu-list">
<li><a href="https://github.com/prashant47">
<span class="icon is-small">
<i class="fa fa-github fa-fw"></i>
</span>
<span class="link-text">GitHub</span>
</a></li>
<li><a href="http://facebook.com/prashantgonarkar">
<span class="icon is-small">
<i class="fa fa-facebook-official fa-fw"></i>
</span>
<span class="link-text">Facebook</span>
</a></li>
<li><a href="https://twitter.com/pgonarkar">
<span class="icon is-small">
<i class="fa fa-twitter fa-fw"></i>
</span>
<span class="link-text">Twitter</span>
</a></li>
<li><a href="https://linkedin.com/in/pgonarkar">
<span class="icon is-small">
<i class="fa fa-linkedin fa-fw"></i>
</span>
<span class="link-text">Linkedin</span>
</a></li>
</ul> <p class="menu-label">License</p>
<ul class="menu-list">
<li>
<a rel="license" href="http://creativecommons.org/licenses/by-sa/4.0/">
<span class="icon is-small">
<i class="fa fa-creative-commons fa-fw"></i>
</span>
<span>CC BY-SA 4.0</span>
</a>
</li>
</ul>
</aside>
</div>
</div>
</div>
<footer class="footer">
<div class="container has-text-centered">
<p class="subtitle">The question of whether a computer can think is no more interesting than the question of whether a submarine can swim.― Edsger W. Dijkstra</p> <p><a href="https://github.com/textbook/bulrush">Bulrush</a> theme for
<a href="https://blog.getpelican.com/">Pelican</a>
| <span class="icon is-small"><i class="fa fa-html5"></i></span> HTML 5
| <span class="icon is-small"><i class="fa fa-css3"></i></span> CSS 3
</p>
</div>
</footer>
<script type="text/javascript">
var disqus_shortname = 'pgonarkar';
(function () {
var s = document.createElement('script'); s.async = true;
s.type = 'text/javascript';
s.src = 'https://' + disqus_shortname + '.disqus.com/count.js';
(document.getElementsByTagName('HEAD')[0] || document.getElementsByTagName('BODY')[0]).appendChild(s);
}());
</script>
<script type="text/javascript">
document.getElementById('navToggle').addEventListener('click', function () {
var nav = document.getElementById('navMenu');
var className = nav.getAttribute('class');
if (className == 'nav-right nav-menu') {
nav.className = 'nav-right nav-menu is-active';
} else {
nav.className = 'nav-right nav-menu';
}
});
</script>
</body>
</html>