pycharm使用python语言连接mysql数据库

首先如图所示,选择Database选项

点击那个+号(因为我已经连接好了,第一次链接页面会为空)

选择MySQL选项

进入本页面后,首先需要下载jar包,具体在Test Connection的上面(我已经下载了,所以没有提示),然后按照自己的数据填进去即可。点击Test Connection后如果显示连接成功,点击OK就行

成功连接的页面

# This is a sample Python script.

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
import pymysql

def print_hi(name):
    # Use a breakpoint in the code line below to debug your script.
    print(f'Hi, {name}')  # Press Ctrl+F8 to toggle the breakpoint.


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    print_hi('PyCharm')
    db = pymysql.connect(
        host='localhost',  ####mysql数据库地址可以输入本机IP,可以是localhost
        # host='localhost'
        port=3306,  ####mysql数据库端口号
        user='root',  ####mysql数据库账号
        passwd='',  #####mysql数据库密码
        database='')  ####mysql数据库库名
    ###使用 cursor() 方法创建一个游标对象 cur
    cur = db.cursor()
    # 使用 execute()  方法执行 SQL 查询
    cur.execute('select version()')
    cur.execute('insert into doctor(Doctor_ID,Gender,Specialty,First_and_last_name,Tel_number) values ("10","female","eat","Alice Bob","123456789")')
    ####使用 fetchone() 方法获取单条数据.fetchall()获取所有数据
    print(cur.fetchall())
    ####关闭数据库连接
    db.commit()
    db.close()


# See PyCharm help at https://www.jetbrains.com/help/pycharm/

运行上述代码,注意本代码段 还没有填写mysql登陆密码和数据库名。

添加成功。

猜你喜欢

转载自blog.csdn.net/ljh1528207303/article/details/124450685