
import mysql.connector
# 连接数据库
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="grad_student_system"
)
# 创建游标对象
mycursor = mydb.cursor()
# 插入一条记录
sql = "INSERT INTO students (student_id, name, major) VALUES (%s, %s, %s)"
val = ("S12345", "Alice Smith", "Computer Science")
mycursor.execute(sql, val)
# 提交事务
mydb.commit()
print(mycursor.rowcount, "record inserted.")
这段代码展示了如何插入一条新的学生记录到数据库中。
from elasticsearch import Elasticsearch
# 创建Elasticsearch客户端
es = Elasticsearch([{'host': 'localhost', 'port': 9200}])
# 索引文档
doc = {
'author': 'John Doe',
'text': 'This is a test document.',
'timestamp': '2023-01-01T12:00:00'
}
res = es.index(index="knowledge_base", id=1, body=doc)
print(res['result'])
这样就可以将文档添加到知识库中。
