编程实现利用DataFrame读写MySQL的数据

(1)在MySQL数据库中新建数据库sparktest,再建表employee,包含下列两行数据;

表1 employee表原有数据

id

name

gender

age

1

Alice

F

22

2

John

M

25

create database sparktest;
use sparktest;
create table employee (id int(4), name char(20), gender char(4), age int(4));
insert into employee values(1,'Alice','F',22);
insert into employee values(2,'John','M',25);
select * from employee 

(2)配置Spark通过JDBC连接数据库MySQL,编程实现利用DataFrame插入下列数据到MySQL,最后打印出age的最大值和age的总和。

表2 employee表新增数据

id

name

gender

age

3

Mary

F

26

4

Tom

M

23

from pyspark import SparkContext
from pyspark.sql import SQLContext
from pyspark.sql.types import Row
from pyspark.sql.types import StructType
from pyspark.sql.types import StructField
from pyspark.sql.types import StringType
from pyspark.sql.types import IntegerType
sc = SparkContext( 'local', 'test')
spark=SQLContext(sc)
jdbcDF=spark.read.format("jdbc").option("url","jdbc:mysql://localhost:3306/sparktest").option("driver","com.mysql.cj.jdbc.Driver").option("dbtable","employee").option("user", "root").option("password", "Gh123456/").load()
jdbcDF.filter(jdbcDF.age>20).collect()
studentRDD = sc.parallelize(["3 Mary F 26","4 Tom M 23"]).map(lambda line : line.split(" "))
schema = StructType([StructField("id",IntegerType(),True),StructField("name", StringType(), True),StructField("gender", StringType(), True),StructField("age",IntegerType(), True)])
rowRDD = studentRDD.map(lambda p : Row(int(p[0]),p[1].strip(), p[2].strip(),int(p[3])))
employeeDF = spark.createDataFrame(rowRDD, schema)
prop = {}
prop['user'] = 'root'
prop['password'] = 'Gh123456/'
prop['driver'] = "com.mysql.cj,jdbc.Driver"
employeeDF.write.jdbc("jdbc:mysql://localhost:3306/sparktest",'employee','append', prop)
jdbcDF.collect()
jdbcDF.agg({"age": "max"}).show()
jdbcDF.agg({"age": "sum"}).show()

 总结

  1.  通过对比MySQL8.0和MySQL5.7了解了mysql8.0更改了validate_password_policy相关的配置名称,这使得修改密码时。密码设置必须要大小写字母数字和特殊符号(,/';:等),不然不能配置成功,如果想使用简单的密码,可以修改MySQL8.0的密码策略。
  2.  编程中也遇到很多问题,如:在安装mysql时报错源……的GPG密钥已安装,但不适用于此安装包。请检查源的公钥URL是否配置正确。解决办法是输入如下命令:具体可以参考我的另一篇博客

    记一次Linux安装mysql报错问题:失败的软件包是:mysql-community-common-8.0.30-1.el7.x86_64

rpm --import https://repo.mysql.com/RPM-GPG-KEY-mysql-2022
yum install -y mysql-community-server
  • 0
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: 利用DataFrame可以将数据以表格的形式存储,然后通过Python内置的MySQL库连接数据库利用pandas的to_sql方法将DataFrame数据写入到MySQL。具体的实现可以参考在网上搜到的相关教程。 ### 回答2: 在Python,可以使用pandas库DataFrame读写MySQL数据库数据。下面是一些必要的步骤: 1. 安装所需的库 需要安装pandas库和mysql-connector-python库。可以使用以下命令进行安装: ``` pip install pandas pip install mysql-connector-python ``` 2. 连接MySQL数据库 使用以下代码可以连接到MySQL数据库: ``` import mysql.connector mydb = mysql.connector.connect( host="localhost", user="yourusername", password="yourpassword", database="mydatabase" ) print(mydb) ``` 3. 查询数据并创建DataFrame 使用pandas库的read_sql()函数可以执行查询并创建DataFrame: ``` import pandas as pd mycursor = mydb.cursor() mycursor.execute("SELECT * FROM customers") myresult = mycursor.fetchall() df = pd.DataFrame(myresult) print(df) ``` 4. 将DataFrame写入MySQL数据库 使用pandas库的to_sql()函数可以将DataFrame写入MySQL数据库: ``` import mysql.connector from sqlalchemy import create_engine engine = create_engine("mysql+mysqlconnector://yourusername:yourpassword@localhost:3306/mydatabase") df.to_sql('customers', con=engine, if_exists='replace', index=False) mycursor = mydb.cursor() mycursor.execute("SELECT * FROM customers") myresult = mycursor.fetchall() for x in myresult: print(x) ``` 以上就是利用DataFrame读写MySQL数据库实现过程。需要注意的是,读写MySQL数据库需要具备MySQL数据库基础知识,如数据库的连接、查询以及表的创建与修改等。 ### 回答3: 在Python,pandas库提供了DataFrame对象,用于处理数据表格。同时,pandas库也提供了读写数据的能力,包括读取数据库数据。在本文,我们将使用pandas库读写MySQL数据。 首先,我们需要准备好MySQL数据库和需要使用的表格。假设我们有以下数据表: ``` CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, `age` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ``` 这个表格包含了用户的ID、姓名和年龄。 接着,我们需要安装MySQLPython驱动程序,可以使用pip install安装mysql-connector-python: ``` pip install mysql-connector-python ``` 接下来,我们需要导入需要的库: ``` import pandas as pd import mysql.connector ``` 连接MySQL数据库: ``` mydb = mysql.connector.connect( host="localhost", user="yourusername", password="yourpassword", database="mydatabase" ) ``` 在这里,我们连接到名为“mydatabase”的数据库。 接下来,我们可以使用pandas.read_sql()函数从MySQL获取数据,如下所示: ``` df = pd.read_sql("SELECT * FROM users", con=mydb) ``` 这将通过MySQL连接对象mydb的SELECT语句检索users表格的所有行并存储在DataFrame对象。 接下来的步骤是修改DataFrame对象并将其写回到MySQL数据库,以下是一个示例: ``` new_row = pd.DataFrame({'id': 4, 'name': 'Tom', 'age': 30}, index=[0]) df = pd.concat([df, new_row]) cursor = mydb.cursor() cursor.execute("TRUNCATE TABLE users") for index, row in df.iterrows(): sql = "INSERT INTO users (name, age) VALUES (%s, %s)" val = (row['name'], row['age']) cursor.execute(sql, val) mydb.commit() ``` 这个示例假设我们要将一个名叫“Tom”的用户添加到数据库。首先,我们使用concat()函数将新行添加到DataFrame对象。然后,我们使用mysql-connector库的cursor()函数获取游标对象并执行一组SQL语句来清空users表格,并将所有行写回数据库。 最后,我们使用MySQL连接对象进行提交操作以确保数据已成功写入MySQL数据库
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小关不摆烂

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值