So, here's one approach to fixing up
this code that you might have taken.
This code here actually has a bad
bug that we'll be looking into next.
So, please don't go copying this
into all your production apps.
So, whenever we want to read or write
to database, we first connect to it.
Then establish a cursor.
Then we do an execute.
In the case of GetAllPosts,
we execute a SELECT statement.
And then we fetch all the results and
reformat them into the dictionary
that our code expects.
And of course, we close
the connection and return the posts.
In the case of AddPost, we still
connect to the database just the same.
We execute an INSERT query,
substituting in the post
content into the query string.
Commit the change and close.
Now, this seems to work, but
I did just say this has a bad bug, and
we're going to see that right up ahead.
إذن، إليك طريقة لإصلاح
.هذه التعليمة البرمجية التي قد تكون أخذتها
في الواقع، تحتوي هذه التعليمة البرمجية على
.خطأ جسيم سنفحصه فيما بعد
لذا، لا تقم بنسخ هذه التعليمة البرمجية
.إلى تطبيقات الإنتاج لديك
إذا أردت قراءة إحدى قواعد البيانات أو الكتابة
.إليها، فاتصل بها أولاً
.وبعد ذلك، قم بإنشاء مؤشر
.وبعدها، نُصدر أمر execute
،في حالة GetAllPosts
.نقوم بتنفيذ عبارة SELECT
وبعد ذلك، نقوم بإحضار كل النتائج
وإعادة تنسيقها في القاموس
.الذي تتوقعه التعليمة البرمجية
وبالطبع، نقوم بإغلاق
.الاتصال وإرجاع المنشورات
أما في حالة AddPost، فسنقوم
.بالاتصال بقاعدة البيانات أيضًا مثل الخطوة السابقة
،وبعد ذلك، سنقوم بتنفيذ استعلام INSERT
الذي يستبدل محتوى
.المنشور في سلسلة الاستعلام
.وبعدها، سنقوم بتثبيت التغييرات وإغلاق الاتصال
والآن، يبدو أن هذه الطريقة ناجحة، ولكنني
قلت سابقًا أن هذه التعليمة البرمجية بها خطأ كبير
.وسنرى ذلك فيما بعد
Aqui está uma abordagem para corrigir
este código que você poderia ter usado.
Esse código aqui tem um bug
sério que vamos analisar em seguida.
Não vá copiar isso
em todos os seus aplicativos de produção.
Sempre que vamos ler ou gravar
no banco de dados, primeiro nos conectamos a ele.
Em seguida, estabelecemos um cursor.
Depois fazemos uma execução.
No caso de GetAllPosts,
executamos uma instrução SELECT.
E depois buscamos todos os resultados e
os reformatamos no dicionário
que nosso código espera.
E, claro, fechamos
a conexão e retornamos as postagens.
No caso de AddPost, ainda nos
conectamos ao banco de dados da mesma forma.
Executamos uma consulta INSERT,
substituindo o conteúdo da
postagem pela string de consulta.
Confirme a alteração e feche.
Agora, isso parece funcionar, mas
acabei de dizer que existe um bug grave e
veremos isso em seguida.
先讲一种修改这段代码的方法 你们有可能会这样写
但实际上 这会引入一个很严重的 bug 我们等会儿再分析
所以先别急着把它们复制到你们的应用里
每当我们想要向数据库进行读写操作时就先要连接它
然后创建一个光标 (cursor)
然后就可以执行
比如说 GetAllPosts 我们执行一个 select 语句
接下来我们就获得了所有的结果
把它们转换成与代码匹配的字典形式
显然 还要关闭连接并返回贴子
对于 AddPost 我们同样要连接数据库
执行一个 insert 语句
把贴子内容放到数据库字符串 query 中
提交改动然后关闭连接
这样似乎是完成任务了 但我刚刚说过 这里有一个很严重的 bug
让我们马上就来看一看