MariaDB无法插入数据

时间:2017-01-13 10:57:56

标签: python mariadb

数据库用户可以从其他位置连接到服务器。他们有访问权限。服务器防火墙已禁用。

import pymysql
def ConnectToDatabase():
    return pymysql.connect(host = "hostName", user = "databaseUserId", password = "databaseUserPw", db = "databaseName", charset = "utf8")

def DisconnectDatabase(databaseConnection) :
    databaseConnection.close()

def ExecuteQueryToDatabase(executeAbleQuery) :
    databaseConnection = ConnectToDatabase()
    databaseResultDataCursor = databaseConnection.cursor()
    databaseResultDataCursor.execute(executeAbleQuery)
    databaseResultDataRows = databaseResultDataCursor.fetchall()
    DisconnectDatabase(databaseConnection)
    return databaseResultDataRows

def ClientRequestQuery(request) :
    dbQuery = request.GET.get('query',';')
    print dbQuery
    return HttpResponse(ExecuteQueryToDatabase(dbQuery))

def TestQuery(request):

    ExecuteQueryToDatabase('insert into User2 (`a`, `b`, `c`, `d`) values(1, 2, 3, 4);');

    return HttpResponse("test")

代码只是连接到MariaDB并插入一些数据, 但是当我尝试这段代码时,数据没有错误,“test”成功返回

表结构是

    MariaDB [ServiceDatabase]> desc User2;
│+-------+---------+------+-----+---------+-------+

│| Field | Type    | Null | Key | Default | Extra |

│+-------+---------+------+-----+---------+-------+

│| a     | int(11) | NO   |     | NULL    |       |

│| b     | int(11) | NO   |     | NULL    |       |

│| c     | int(11) | NO   |     | NULL    |       |

│| d     | int(11) | NO   |     | NULL    |       |

│+-------+---------+------+-----+---------+-------+

│4 rows in set (0.00 sec)

Django版本是10.0.2 Python版本是2.7.12

任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

您在代码中的任何位置都没有执行merge(x, z, by = "row.names")[-1] # a1.x b1 a1.y b2 #1 1 a 4 d #2 2 b 5 e #3 3 c 6 f 。使用python在数据库上执行插入的一般方法是

1)创建连接和光标

commit

2)执行insert,然后在事务失败时提交或回滚

 conn = MySQLdb.connect(host= "hostname",
              user="root",
              passwd="password",
              db="dbname")
 x = conn.cursor()

据我所见,您永远不会执行try: x.execute("INSERT INTO User2 (a, b, c, d) VALUES (%s, %s, %s, %s)", (1,2,3,4)) conn.commit() except: conn.rollback() conn.close() ,因此交易实际上从未完成。

答案 1 :(得分:-1)

使用 mariadb 连接器并设置 autocommit=True 之类的

# Module Import
import mariadb

# Instantiate Connection
try:
conn = mariadb.connect(
    user="john",
    password="secret",
    host="localhost",
    port=3306,
    autocommit=True)
    
except mariadb.Error as e:
print(f"Error connecting to MariaDB Platform: {e}")
sys.exit(1)