A cursor is an iterator that gives rows after executing a SELECT statement. For example, instead of retrieving all the results in a list with
rows = cur.fetchall()
You can iterate over strings with
for row in cur:
However, since the NetworkX method add_weighted_edges_from accepts an iterator, you can pass cur directly:
G.add_weighted_edges_from(cur)
This is a good example of polymorphism. NetworkX designers did not need to do anything special or even expect sqlite3 cursors to be passed as an argument; they only needed to write code with the assumption that the iterator was the first argument.
import networkx as nx import sqlite3 import matplotlib.pyplot as plt with sqlite3.connect(":memory:") as con: cur = con.cursor() cur.execute("CREATE TABLE DATEN(Source TEXT, Target TEXT, Weight REAL)") cur.execute("INSERT INTO DATEN VALUES('X33', 'X20', 0.014)") cur.execute("INSERT INTO DATEN VALUES('X32', 'X20', 0.024)") cur.execute("INSERT INTO DATEN VALUES('X23', 'X20', 0.167)") cur.execute("INSERT INTO DATEN VALUES('X23', 'X32', 0.015)") cur.execute("INSERT INTO DATEN VALUES('X32', 'X33', 0.003)") cur.execute("INSERT INTO DATEN VALUES('X23', 'X33', 0.035)") G = nx.Graph() cur.execute('SELECT Source, Target, Weight FROM DATEN') G.add_weighted_edges_from(cur) nx.draw(G) plt.show()

source share