在python中使用MySQLdb连接到数据库

时间:2015-11-03 17:49:43

标签: python mysql

所以基本上我只是想试试这个:

import MySQLdb

conn = MySQLdb.connect(host="myhost.com",    user="myusername", passwd="mypassword", db="nameofmydatabase")

query = "INSERT INTO nameofmydatabase (columntitle) values ('sampletext')"
x = conn.cursor()
x.execute(query)
row = x.fetchall()

所以这是我得到的错误。我在错误中更改了我的实际信息,但我想知道如何解决这个问题。

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "write2MySQL_test.py", line 3, in <module>
    conn = MySQLdb.connect(host="myhost.com", user="myusername", passwd="mypassword", db="nameofmydatabase")
  File "/usr/local/lib/python2.7/site-packages/MySQLdb/__init__.py", line 81, in Connect
    return Connection(*args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/MySQLdb/connections.py", line 193, in __init__
    super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (2003, "Can't connect to MySQL server on  'myhost.com' (60)")

2 个答案:

答案 0 :(得分:2)

您是否尝试过手动连接MySQL数据库? (使用PhpMyAdmin或MySQL查询浏览器等) 您是否能够从正在运行代码的计算机上访问数据库? ping ip以查看是否有防火墙。

另外,我不确定你是如何设置的,是myhost.com指向什么?你的意思是localhost吗?

编辑 -

尝试使用这样的端口

db = MySQLdb.connect(
    host = 'localhost', 
    user = 'root', 
    passwd = '', 
    db = 'dbname', 
    port = 3306)

我不确定您的数据库是否被称为“nameofmydatabase”,因此请确保填写相应的字段。

答案 1 :(得分:0)

主机名错误,您可以使用&#34; localhost&#34;代替&#34; myhost.com&#34;。 我已经创建了一个用于连接和查询Db的示例类。

您可以使用以下代码连接到数据库。 更改uname,passwd和数据库名称的值

import MySQLdb
class DbFunctions(object):
    def _ _init_ _(self,server,uname,passwd,dbname):
        self.server = server
        self.uname = uname
        self.passwd = passwd
        self.dbname = dbname
        self.db = None
        self.cur = None

    def connection_open(self):
        self.db = MySQLdb.connect(host=self.server,user=self.uname,passwd=self.password,db=self.dbname)
        self.cur = self.db.cursor()

    def connection_close(self):
        self.db.close()

    def mysql_qry(self,sql,bool): # 1 for select and 0 for insert update delete
        self.connection_open()
        try:
            self.cur.execute(sql)
            if bool:
                return self.cur.fetchall()
            else:
                self.db.commit()
                return True
        except MySQLdb.Error, e:
            try:
                print "Mysql Error:- "+str(e)
            except IndexError:
                print "Mysql Error:- "+str(e)
        self.connection_close()

    def mysql_insert(self,table,fields,values):
        sql = "INSERT INTO " + table + " (" + fields + ") VALUES (" + values + ")";
        return self.mysql_qry(sql,0)

    def mysql_update(self,table,values,conditions):
        sql = "UPDATE " + table + " SET " + values + " WHERE " + conditions
        return self.mysql_qry(sql,0)

    def mysql_delete(self,table,condtions):
        sql = "DELETE FROM " + table + " WHERE " + condition;
        return self.mysql_qry(sql,0)

    def mysql_select(self,table):
        sql =  "SELECT * FROM "+table
        return self.mysql_qry(sql,1)

`db = DbFunctions(&#34; localhost&#34;,&#34; uname&#34;,&#34; passwd&#34;,&#34; database_name&#34;)

您可以查看我的github帐户的以下链接,了解更多详情 https://github.com/pantlavanya/codes/blob/master/db_function_library.py