db.execSQL("select * from user where name ="+name);

时间: 2024-02-21 18:57:49 浏览: 30
在执行SQL语句时,应该使用`query()`或`rawQuery()`方法,而不是`execSQL()`方法。`execSQL()`方法用于执行不返回结果集的SQL语句,例如CREATE、UPDATE、DELETE等语句,而`query()`或`rawQuery()`方法用于执行SELECT查询语句并返回结果集。另外,你应该使用参数化查询,避免SQL注入攻击。正确的写法如下: ``` Cursor cursor = db.rawQuery("SELECT * FROM user WHERE name = ?", new String[]{name}); ``` 这个语句使用了`rawQuery()`方法,并采用了参数化查询的方式,其中`?`表示占位符,`new String[]{name}`表示将`name`作为参数传入SQL语句中。这样可以确保查询语句的正确性,并避免SQL注入攻击。
相关问题

db.execSQL("update user set Name=? ,Nickname=?,Age=?",new Object[]{name,nickname,age}); Cursor cursor= db.rawQuery("select*from user where Account=?",new String[]{account}); editTextname.setText(cursor.getString(2)); editTextnickname.setText(cursor.getString(3)); editTextage.setText(cursor.getString(4)); cursor.close();显示更新的数据哪错了

这段代码有几个问题: 1. `update` 语句中的参数应该是按照字段的顺序传递的,而不是按照字段名称。因此,应该将 `Name`、`Nickname`、`Age` 改为对应的字段顺序(假设是第 2、3、4 个字段)。 2. 在执行 `rawQuery` 方法时,需要先调用 `moveToFirst` 方法将结果集指针移动到第一条记录上,然后才能获取数据。因此,在调用 `cursor.getString` 方法之前,应该先调用 `cursor.moveToFirst` 方法。 修改后的代码应该是这样的: ``` db.execSQL("update user set ?, ?, ? where Account=?", new Object[]{name, nickname, age, account}); Cursor cursor = db.rawQuery("select * from user where Account=?", new String[]{account}); if (cursor.moveToFirst()) { editTextname.setText(cursor.getString(2)); editTextnickname.setText(cursor.getString(3)); editTextage.setText(cursor.getString(4)); } cursor.close(); ```

from PyQt5 import QtWidgets, QtSql import sys class Login(QtWidgets.QWidget): def __init__(self): super().__init__() self.init_ui() def init_ui(self): # 创建控件 self.username = QtWidgets.QLineEdit() self.password = QtWidgets.QLineEdit() self.password.setEchoMode(QtWidgets.QLineEdit.Password) self.login_btn = QtWidgets.QPushButton('登录') # 创建布局 layout = QtWidgets.QVBoxLayout() layout.addWidget(QtWidgets.QLabel('用户名')) layout.addWidget(self.username) layout.addWidget(QtWidgets.QLabel('密码')) layout.addWidget(self.password) layout.addWidget(self.login_btn) # 设 置布局 self.setLayout(layout) # 链接数据库 db = QtSql.QSqlDatabase.addDatabase('QSQLITE') db.setDatabaseName('test.db') if not db.open(): QtWidgets.QMessageBox.critical(None, "无法打开数据库", "无法建立到数据库的连接,这个例子需要SQLite支 持,请检查数据库配置\n\n" "点击取消退出应用程序", QtWidgets. QMessageBox.Cancel) return # 创建表格 query = QtSql.QSqlQuery() query.exec_("create table user (id int primary key, username varchar(20), password varchar(20))") query.exec_("insert into user values(1, 'admin', 'admin')") # 链接信号和槽 self.login_btn.clicked.connect(self.login) def login(self): username = self.username.text().strip() password = self.password.text().strip() # 验证用户名和密码 query = QtSql.QSqlQuery() sql = "select * from user where username='{0}' and password='{1}'".format(username, password) query.exec_(sql) if query.next(): QtWidgets.QMessageBox.information(None, '登录成功 ', '登录成功') else: QtWidgets.QMessageBox.warning(None, '登录失败', '用户名或密码错误') if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) window = Login() window.show() sys.exit(app.exec_())

这是一个使用PyQt5连接SQLite数据库实现登录功能的示例代码。代码中通过创建控件、布局以及链接信号和槽等方式实现了一个简单的登录界面。其中,通过QtSql模块连接SQLite数据库,并创建了一个名为"user"的表格,用于存储用户信息。在登录时,通过查询用户输入的用户名和密码是否在数据库中存在来验证用户身份,并弹出相应的提示框。

相关推荐

import os import tkinter as tk from tkinter import ttk import pymssql import smtplib from email.mime.multipart import MIMEMultipart from email.header import Header from email.mime.text import MIMEText host = '..*.**' user = 'sa' password = '123456789' database = 'deste' class MSSQL: """""" def init(self): self.db_config = {"host": host, "user": user, "password": password, "database": database} def __get_connect(self, charset='utf8'): try: # 实例化连接对象 self.conn = pymssql.connect(**self.db_config, charset=charset) cur = self.conn.cursor() except pymssql.DatabaseError: print('连接失败') cur = '' else: print('连接成功') return cur def exec_query(self, str_sql): cur = self.__get_connect(charset='GBK') cur.execute(str_sql) results_list = cur.fetchall() cur.close() self.conn.close() return results_list def exec_non_query(self, str_sql): cur = self.__get_connect() cur.execute(str_sql) self.conn.commit() cur.close() self.conn.close() def zhaowenjian(list_result): ''' 需要查找的关键字列表 和对应的path ''' print(list_result) result1 = [item[3] + item[2] for item in list_result if item[0] == 6] result2 = [item[3] + item[2] for item in list_result if item[0] == 2] path1 = 'E:/出货报告/5604' path2 = 'E:/出货报告1/5604' keywords1 = result1 keywords2 = result2 ''' 找到文件路径 ''' file_dict = {} for pn in keywords1: file_dict[pn] = [] for pn in keywords2: file_dict[pn] = [] for root, dirs, files in os.walk(path1): for file in files: for keyword in keywords1: if keyword in file: file_dict[keyword].append(os.path.join(root, file)) for root, dirs, files in os.walk(path2): for file in files: for keyword in keywords2: if keyword in file: file_dict[keyword].append(os.path.join(root, file)) print(file_dict) for key,value in file_dict.items(): print(key,value,len(value)) return file_dict def show_file_dict(): file_dict = zhaowenjian(list_result) if name == 'main': Sql = """SELECT [WHSE_PTR] , [SALES_ORDER] , [CP_REV] , [CUSTOMER_PART_NUMBER] , [INTIME] , [stat] FROM[fineReport].[dbo].[lCSRM5604] where stat = 1""" list = MSSQL().exec_query(Sql) list_result = list zhaowenjian(list_result) show_file_dict() 在Django中调用这个py文件的代码

#include "mainwindow.h" #include "ui_mainwindow.h" #include<QDebug> #include<QMessageBox> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); //登录 stu = new studentt; connect(ui->pushButton,&QPushButton::clicked,this,&MainWindow::logon); connect(stu,&studentt::RturnLogon,this,[=]{ stu->hide(); this->show(); }); //注册 User_Registers = new registers; connect(ui->pushButton_2,&QPushButton::clicked,this,&MainWindow::registerss); connect(User_Registers,®isters::Show_Main,this,[=](){ this->show(); User_Registers->hide(); }); ui->lineEdit_2->setEchoMode(QLineEdit::Password); } MainWindow::~MainWindow() { delete ui; } //数据库链接 void MainWindow::opensql() { db = QSqlDatabase::addDatabase("QODBC"); db.setPort(3306); db.setDatabaseName("sql"); db.setUserName("root"); db.setPassword("123456"); db.open(); } void MainWindow::logon() { //"select * from username where username like '1122' and password like '221'" QString s = "select * from username where username like \'"+ui->lineEdit->text()+"\'"+"and password like \'"+ ui->lineEdit_2->text()+"\'"; opensql(); qDebug()<<s; //账号密码传到数据库执行 result = db.exec(s); if (result.next()) { //判断权限 n = result.value("auth").toInt(); this->hide(); stu->show(); connect(this,&MainWindow::User_Name,stu,&studentt::set_UserName); emit User_Name(ui->lineEdit->text()); } else { QMessageBox::about(this,"提示","账号或密码输入错误请重新输入"); ui->lineEdit->clear(); ui->lineEdit_2->clear(); } } void MainWindow::registerss() { User_Registers->show(); this->hide(); } 分析

class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setFixedSize(800, 600) main_layout = QVBoxLayout() central_widget = QWidget() central_widget.setLayout(main_layout) self.setCentralWidget(central_widget) button_layout = QVBoxLayout() button1 = QPushButton('当日员工工资') button1.setFixedSize(200, 50) button1.clicked.connect(self.show_query1_result) button_layout.addStretch() button_layout.addWidget(button1) button_layout.addStretch() layout = QHBoxLayout() layout.addStretch() layout.addLayout(button_layout) layout.addStretch() widget = QWidget() widget.setLayout(layout) self.setCentralWidget(widget) main_layout.addLayout(button_layout) self.query1_window = QueryResultWindow() def show_query1_result(self): db = pymysql.connect(host='39.99.214.172', user='root', password='Solotion.123', db='jj_tset') cursor = db.cursor() db_sql = """ """ cursor.execute(db_sql) result = cursor.fetchall() db.close() if len(result) == 0: QMessageBox.information(self, "提示", "今日无员工工资记录") return self.query1_window.table_widget.setRowCount(0) self.query1_window.table_widget.setColumnCount(len(result[0])) self.query1_window.table_widget.setHorizontalHeaderLabels( ["员工ID", "员工姓名", "日期", "领取鸡爪重量(KG)", "效率(每小时KG)", "出成率", "基础工资", "重量奖励", "当日总工资"]) for row_num, row_data in enumerate(result): self.query1_window.table_widget.insertRow(row_num) for col_num, col_data in enumerate(row_data): self.query1_window.table_widget.setItem(row_num, col_num, QTableWidgetItem(str(col_data))) self.query1_window.show() class QueryResultWindow(QWidget): def __init__(self): super().__init__() self.setFixedSize(800, 600) self.table_widget = QTableWidget() self.table_widget.setEditTriggers(QTableWidget.NoEditTriggers) self.table_widget.setSelectionBehavior(QTableWidget.SelectRows) layout = QVBoxLayout() layout.addWidget(self.table_widget) self.setLayout(layout) if __name__ == '__main__': app = QApplication(sys.argv) loginWindow = LoginWindow() loginWindow.show() sys.exit(app.exec_()))数据展示页面怎么设置筛选器按ID筛选结果并展示

class MainWindow(QMainWindow): def init(self): super().init() # 设置主窗口大小 self.setFixedSize(800, 600) # 创建主窗口布局 main_layout = QVBoxLayout() central_widget = QWidget() central_widget.setLayout(main_layout) self.setCentralWidget(central_widget) # 创建两个竖向按钮 button_layout = QVBoxLayout() button1 = QPushButton('当日员工工资') button1.setFixedSize(200, 50) button1.clicked.connect(self.show_query1_result) button2 = QPushButton('当日鸡爪领取记录') button2.setFixedSize(200, 50) button2.clicked.connect(self.show_query2_result) button3 = QPushButton('查询历史员工工资') button3.setFixedSize(200, 50) button3.clicked.connect(self.show_query3_result) button4 = QPushButton('查询历史鸡爪领取记录') button4.setFixedSize(200, 50) button4.clicked.connect(self.show_query4_result) button_layout.addStretch() button_layout.addWidget(button1) button_layout.addWidget(button2) button_layout.addWidget(button3) button_layout.addWidget(button4) button_layout.addStretch() layout = QHBoxLayout() layout.addStretch() layout.addLayout(button_layout) layout.addStretch() widget = QWidget() widget.setLayout(layout) self.setCentralWidget(widget) # 将按钮布局添加到主窗口布局中 main_layout.addLayout(button_layout) # 创建两个窗口用于展示查询结果 self.query1_window = QueryResultWindow() self.query2_window = QueryResultWindow() self.query3_window = QueryResultWindow() self.query4_window = QueryResultWindow() def show_query1_result(self): # 查询数据 db = pymysql.connect(host='39.99.214.172', user='root', password='Solotion.123', db='jj_tset') cursor = db.cursor() db_sql = """ """ cursor.execute(db_sql) result = cursor.fetchall() db.close() if len(result) == 0: QMessageBox.information(self, "提示", "今日无员工工资记录") return # 清空表格 self.query1_window.table_widget.setRowCount(0) self.query1_window.table_widget.setColumnCount(len(result[0])) self.query1_window.table_widget.setHorizontalHeaderLabels \ (["员工ID", "员工姓名", "日期", "领取鸡爪重量(KG)", "效率(每小时KG)", "出成率", "基础工资", "重量奖励", "当日总工资"]) # 添加数据到表格 for row_num, row_data in enumerate(result): self.query1_window.table_widget.insertRow(row_num) for col_num, col_data in enumerate(row_data): self.query1_window.table_widget.setItem(row_num, col_num, QTableWidgetItem(str(col_data))) # 显示窗口 self.query1_window.show()数据展示页面怎么设置筛选器按ID筛选结果并展示

最新推荐

recommend-type

6-10.py

6-10
recommend-type

基于机器学习的入侵检测系统+源码+说明.zip

基于机器学习的入侵检测系统+源码+说明.zip
recommend-type

matlab基于潜在低秩表示的红外与可见光图像融合.zip

matlab基于潜在低秩表示的红外与可见光图像融合.zip
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

2. 通过python绘制y=e-xsin(2πx)图像

可以使用matplotlib库来绘制这个函数的图像。以下是一段示例代码: ```python import numpy as np import matplotlib.pyplot as plt def func(x): return np.exp(-x) * np.sin(2 * np.pi * x) x = np.linspace(0, 5, 500) y = func(x) plt.plot(x, y) plt.xlabel('x') plt.ylabel('y') plt.title('y = e^{-x} sin(2πx)') plt.show() ``` 运行这段
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。
recommend-type

"互动学习:行动中的多样性与论文攻读经历"

多样性她- 事实上SCI NCES你的时间表ECOLEDO C Tora SC和NCESPOUR l’Ingén学习互动,互动学习以行动为中心的强化学习学会互动,互动学习,以行动为中心的强化学习计算机科学博士论文于2021年9月28日在Villeneuve d'Asq公开支持马修·瑟林评审团主席法布里斯·勒菲弗尔阿维尼翁大学教授论文指导奥利维尔·皮耶昆谷歌研究教授:智囊团论文联合主任菲利普·普雷教授,大学。里尔/CRISTAL/因里亚报告员奥利维耶·西格德索邦大学报告员卢多维奇·德诺耶教授,Facebook /索邦大学审查员越南圣迈IMT Atlantic高级讲师邀请弗洛里安·斯特鲁布博士,Deepmind对于那些及时看到自己错误的人...3谢谢你首先,我要感谢我的两位博士生导师Olivier和Philippe。奥利维尔,"站在巨人的肩膀上"这句话对你来说完全有意义了。从科学上讲,你知道在这篇论文的(许多)错误中,你是我可以依
recommend-type

实现实时监控告警系统:Kafka与Grafana整合

![实现实时监控告警系统:Kafka与Grafana整合](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X2pwZy9BVldpY3ladXVDbEZpY1pLWmw2bUVaWXFUcEdLT1VDdkxRSmQxZXB5R1lxaWNlUjA2c0hFek5Qc3FyRktudFF1VDMxQVl3QTRXV2lhSWFRMEFRc0I1cW1ZOGcvNjQw?x-oss-process=image/format,png) # 1.1 Kafka集群架构 Kafka集群由多个称为代理的服务器组成,这