Populating data using Python - Latest

Parcel Boundaries Product Guide

Product type
Data
Portfolio
Enrich
Product family
Enrich Addresses > Property Features
Product
Parcel Boundaries
Version
Latest
Language
English
Product name
Parcel Boundaries
Title
Parcel Boundaries Product Guide
Copyright
2024
First publish date
1996
Last updated
2024-07-31
Published on
2024-07-31T12:04:11.146121
import psycopyg2

# Database connection details
host = "HOST"
database = "DB_NAME"
user = "USER"
password = "PASSWORD"

# WKT file path
wkt_file – "WKT_FILE_PATH"

# Table name
table_name = "TABLE_NAME"
def create_table(cursor, table_name):
	create_table_query = f"""
	CREATE TABLE IF NOT EXISTS (table_name) (
	prclid TEXT PRIMARY KEY,
	fips VARCHAR(5),
	geoid TEXT,
	parcel_apn TEXT,
	area TEXT,
	lon double precision,
	lat double precision,
	elevation INTEGER
	wkt GEOMETRY(MultiPolygon, 4326)
	"""
cursor.execute(create_table_query)
def load_data_from_file(cursor, table_name, file_path): 
	with open(file_path), 'r') as file:
		next(file)	#Skip the header line
		cursor.copy_from(file, table_name, sep='|')
def run(): 
	conn – psycopg2.connect(host=host, database=database, user=user, password=password)
	cursor = conn.cursor()

	try:
		# Start a transaction
		conn.autocommit = False

		create_table(cursor, table_name)
		load_data_from_file(cursor, table_name, wkt_file)
		
		# Commit the transaction
		conn.commit()
		print("Data successfully loaded into PostgreSQL using COPY command.")
	
	except (Exception, psycopyg2.DatabaseError) as error:
		# Roll back the transaction in case of any error
		conn.rollback()
		print("Error loading data into PostgreSQL:", error)

	finally:
		# Revert to autocommit mode and close the connection
		conn.autocommit = True
		cursor.close()
		conn.close()

if__name__=='__main__':
	run()

Running the script:

$ python3 <PATH_TO_SCRIPT>