Node.js+MySQL更新数据

在本教程中,您将学习如何从node.js应用程序更新MySQL数据库中的数据。

要从node.js应用程序更新数据,请使用以下步骤:

要连接到MySQL数据库,我们将使用以下config.js模块,其中包含MySQL数据库服务器的必要信息,包括主机,用户,密码和数据库。

let config = {
  host    : 'localhost',
  user    : 'root',
  password: '123456',
  database: 'todoapp'
};

module.exports = config;

更新数据示例

以下update.js程序根据特定的ID来更新托管的状态。

let mysql = require('mysql');
let config = require('./config.js');

let connection = mysql.createConnection(config);

// update statment
let sql = `UPDATE todos
           SET completed = ?
           WHERE id = ?`;

let data = [false, 1];

// execute the UPDATE statement
connection.query(sql, data, (error, results, fields) => {
  if (error){
    return console.error(error.message);
  }
  console.log('Rows affected:', results.affectedRows);
});

connection.end();

在这个例子中,我们在UPDATE语句中使用了占位符(?)。

当通过在连接对象上调用query()方法执行UPDATE语句时,以数组的形式将数据传递给UPDATE语句。 占位符将被数组中的值替换为数组。 在这个例子中,将id1的那条记录的completed列将被设置为false

回调函数的results参数有affectedRows属性,返回UPDATE语句更新的行数。

在执行程序之前,请查看todos表中id1的行记录信息:

mysql> SELECT * FROM todos WHERE id = 1;
+----+-------------------------------+-----------+
| id | title                         | completed |
+----+-------------------------------+-----------+
|  1 | Learn how to insert a new row |         1 |
+----+-------------------------------+-----------+
1 row in set (0.00 sec)

现在,我们来运行上面update.js程序。

F:\worksp\mysql\nodejs\nodejs-connect>node update.js
openssl config failed: error:02001003:system library:fopen:No such process
Rows affected: 1

程序返回一条消息,指示受影响的行数为1, 我们可以在数据库中再次查看它,如下所示:

mysql> SELECT * FROM todos WHERE id = 1;
+----+-------------------------------+-----------+
| id | title                         | completed |
+----+-------------------------------+-----------+
|  1 | Learn how to insert a new row |         0 |
+----+-------------------------------+-----------+
1 row in set (0.00 sec)

您可以看到,completed列中的值已更新为0,在node.js中为false

在本教程中,我们向您展示了如何从node.js应用程序更新MySQL中的数据。

易百教程移动端:请扫描本页面底部(右侧)二维码并关注微信公众号,回复:”教程” 选择相关教程阅读或直接访问:http://m.yiibai.com 。

上一篇:MySQL+Python连接和操作
下一篇:哥,这回真没有了

加QQ群啦,易百教程官方技术学习群

注意:建议每个人选自己的技术方向加群,同一个QQ最多限加 3 个群。

  • Java技术群: 227270512 (人数:2000,免费:否)
  • MySQL/SQL群: 418407075 (人数:2000,免费:否)
  • 大数据开发群: 655154550 (人数:2000,免费:否)
  • Python技术群: 287904175 (人数:2000,免费:否)
  • 人工智能深度学习: 456236082 (人数:2000,免费:否)
  • 测试工程师(新群): 415553199 (人数:1000,免费:否)
  • 前端技术群(新群): 410430016 (人数:1000,免费:是)
  • C/C++技术(新群): 629264796 (人数:1000,免费:是)
  • Node.js技术(新群): 621549808 (人数:1000,免费:是)
  • PostgreSQL数据库(新群): 539504187 (人数:1000,免费:是)
  • Linux技术: 479429477 (人数:2000,免费:否)
  • PHP开发者: 460153241 (人数:2000,免费:否)
  • Oracle数据库: 175248146 (人数:2000,免费:否)
  • C#/ASP.Net开发者: 579821706 (人数:2000,免费:是)
  • 数据分析师: 397883996 (人数:2000,免费:是)R语言,Matlab语言等技术

96 Responses

  1. Bvxaqt说道:

    furosemide usa lasix 100mg without prescription albuterol drug

  2. Uteplenie_et说道:

    Эффективное тепловая изоляция фасадов — прекрасие и экономия в семейном домовладении!
    Согласитесь, ваш недвижимость заслуживает наилучшего! Изоляция наружных стен – не всего лишь решение для экономии на отоплении, это инвестиция в комфорт и долголетие вашего дома.
    ✨ Почему изоляция с специалистами?
    Искусство: Наша бригада – компетентные. Мы все заботимся о каждой детали, чтобы обеспечить вашему недвижимости идеальное термоизоляция.
    Стоимость услуги изоляции: Мы ценим ваш финансовые ресурсы. Утепление стен дома снаружи цена – начиная от 1350 руб./кв.м. Это инвестиция в ваше удовлетворительное будущее!
    Энергосберегающие решения: Забудьте о теплопотерях! Наши не только сохраняют тепловую энергию, но и дарят вашему коттеджу новый уровень тепла энергоэффективности.
    Преобразуйте свой дом комфортным и изысканным!
    Подробнее на http://n-dom.ru/

    Не передавайте свой дом на волю случая. Доверьтесь нашей команде и создайте тепло вместе с нашей командой!

  3. Vcdech说道:

    order lexapro 10mg generic order lexapro 10mg generic order revia 50mg for sale

  4. Srydiv说道:

    cost atomoxetine buy seroquel 50mg sale buy zoloft 50mg generic

  5. Ettyrc说道:

    cost zithromax 250mg azithromycin 250mg ca neurontin price

  6. Bkvbum说道:

    cost ursodiol 300mg buy bupropion 150 mg pill buy cetirizine pills for sale

  7. Iayufq说道:

    order prednisone 10mg generic isotretinoin 40mg us buy amoxicillin without prescription

  8. Hstgpm说道:

    best fast acting heartburn medication chewable indigestion tablets best tablet for bloating stomach

  9. Hnvngx说道:

    brand promethazine 25mg order phenergan online cheap stromectol canada

  10. Ithyqi说道:

    online prescription for birth control is prostatitis caused by bacteria will cialis make me harder

  11. Grstkr说道:

    duodenal ulcer diagnostic tests best injection for esophagus ulcer antiseptic for urinary tract infection

  12. Slqpjj说道:

    cheap cymbalta 40mg order glipizide 10mg pills cheap provigil 100mg

  13. Vlxxzi说道:

    fungus killer for skin cheapest herpes medication blood pressure medication brand names

  14. Ylebcd说道:

    buy periactin 4mg pills buy nizoral 200 mg pill nizoral online order

  15. Rgfchr说道:

    list of common antiviral drugs basic medicine for diabetes anti diabetic given to paedes

  16. Kzdgdy说道:

    medroxyprogesterone drug microzide over the counter oral microzide 25 mg

  17. Isyira说道:

    drugs that help stop smoking prescription meds for quitting smoking pain medications online to buy

  18. Yemzvc说道:

    femara 2.5mg cheap order aripiprazole 20mg for sale purchase aripiprazole generic

  19. Hrmapf说道:

    get insomnia medication online order sleeping tablets online uk semaglutide weight loss prescription online

  20. BVZ_Moskva_m说道:

    Быстромонтажные здания: экономический доход в каждой части!
    В современном обществе, где моменты – финансы, объекты быстрого возвода стали решением по сути для предпринимательства. Эти современные сооружения включают в себя высокую надежность, финансовую эффективность и мгновенную сборку, что обуславливает их лучшим выбором для разнообразных предпринимательских инициатив.
    Быстровозводимые здания под ключ
    1. Высокая скорость возвода: Секунды – самое ценное в экономике, и скоростроительные конструкции позволяют существенно сократить время монтажа. Это преимущественно важно в сценариях, когда срочно требуется начать бизнес и начать извлекать прибыль.
    2. Экономия средств: За счет улучшения производственных процедур элементов и сборки на объекте, экономические затраты на моментальные строения часто остается меньше, по отношению к обычным строительным проектам. Это предоставляет шанс сократить издержки и получить лучшую инвестиционную отдачу.
    Подробнее на https://scholding.ru
    В заключение, экспресс-конструкции – это идеальное решение для бизнес-мероприятий. Они сочетают в себе эффективное строительство, экономическую эффективность и надежность, что сделало их первоклассным вариантом для деловых лиц, имеющих целью быстрый бизнес-старт и получать прибыль. Не упустите возможность сократить затраты и время, идеальные сооружения быстрого монтажа для ваших будущих проектов!

  21. Fxdxej说道:

    order alfuzosin 10mg for sale buy uroxatral 10mg generic pain relief without stomach upset

  22. Field说道:

    With this service, crypto wallet users in the US can directly convert their crypto holdings into USD and have the funds available in their PayPal balance.  Bitcoin market price is updated every three minutes and is automatically displayed in USD. Below are the most popular denominations to convert to USD. A set amount of Bitcoin is unlocked with each block that is discovered through the mining process. In order for miners to discover and search for new blocks, they use powerful computers that are also known as nodes. Keep in mind that running a node will consume a lot of energy and storage power. In April, exchanges BitInstant and Mt. Gox experienced processing delays due to insufficient capacity resulting in the bitcoin price dropping from $266 to $76 before returning to $160 within six hours. The bitcoin price rose to $259 on 10 April, but then crashed by 83% to $45 over the next three days.
    https://troyvyvu529782.blogspothub.com/22429515/manual-article-review-is-required-for-this-article
    You see, Bitcoin itself is not compatible with Uniswap, or any other DeFi project. Bitcoin runs on a different network to Uniswap, which runs on Ethereum. Think about it as trying to download an Android app onto your iPhone – it just won’t work. In the case of the Android app, a workaround would be to create a version of the app that is specifically designed for iPhone. Every wBTC is an ERC20 coin that is equal to BTC on a 1:1 ratio. You can change any bitcoin to wrapped-BTC on several exchanges, including centralized exchanges. Wrapped BTC can also be converted to bitcoin when you wish. This adaptable and modifiable feature enables users to smoothly swap between BTC and wrapped BTC to meet their needs. WBTC owners can wrap and unwrap their assets at any time. Numerous projects offer the ability to do so, and the process itself is relatively cheap. A hardcore BTC maximalist could, at one point, hold onto his coins and then switch to wrapped bitcoin in order to temporarily diversify his assets by swapping WBTC for a DeFi token.

  23. Xytlbd说道:

    catapres 0.1 mg sale purchase clonidine pills buy tiotropium bromide 9mcg online cheap

  24. Thevgd说道:

    prescription acne medication for adults adult female acne trileptal oral

  25. Wfovyr说道:

    buy amoxicillin pills for sale buy anastrozole 1mg online order clarithromycin 500mg online cheap

  26. Wtejev说道:

    generic calcitriol buy labetalol 100 mg pill order tricor 160mg online cheap

  27. Otzrzk说道:

    teach me how to write an essay 6th grade essay writing worksheets buy cheap generic suprax

  28. Thakla说道:

    letter writing services slots games free slot machine games

  29. Ahsfsf说道:

    lamisil for sale online casino play slots free online

  30. Oaxjhi说道:

    how to get aspirin without a prescription burton brunette casino near me

  31. Jaffeq说道:

    buy trazodone 50mg generic buy sildenafil 50mg for sale clindac a gel

  32. Wwxntd说道:

    buy tadacip tablets voltaren 50mg cost purchase indomethacin pills

  33. Jihzco说道:

    ceftin generic buy generic methocarbamol 500mg order methocarbamol 500mg sale

  34. Vrjfdv说道:

    retin online order buy generic tretinoin over the counter avanafil where to buy

  35. Rfwzlz说道:

    buy nolvadex sale order betahistine online cheap rhinocort canada

  36. Yvnect说道:

    buy lamictal paypal buy mebendazole online cheap buy generic nemazole for sale

  37. Qdarub说道:

    cleocin for sale erythromycin 500mg canada order fildena 50mg for sale

  38. Yacivz说道:

    metronidazole 200mg tablet metronidazole 200mg for sale buy keflex 250mg generic

  39. Nzpdal说道:

    aurogra online order aurogra for sale estrace 2mg oral

  40. Ttqjdt说道:

    buy generic fluconazole buy ampicillin medication buy ciprofloxacin paypal

  41. Cyenin说道:

    help me write my research paper affordable essay writing college paper help

  42. Bassam说道:

    buy spironolactone 100mg without prescription cost valacyclovir 500mg buy generic propecia online

  43. Ydrktt说道:

    buy generic motilium online order coreg 6.25mg for sale order tetracycline online

  44. Yggckv说道:

    generic tamsulosin zocor 10mg generic zocor order online

  45. Xycfst说道:

    generic buspin buy buspirone without prescription buy cordarone 100mg without prescription

  46. Ysafza说道:

    generic zantac 300mg buy mobic 7.5mg online cheap celebrex pill

  47. Rofakz说道:

    buy zyloprim paypal allopurinol order online rosuvastatin 20mg oral

  48. Pjxhhq说道:

    buy generic sumatriptan 25mg cheap levofloxacin 500mg order avodart 0.5mg generic

  49. Jvvqrp说道:

    azelastine sale avalide uk buy avalide pills

  50. Hdywqh说道:

    generic nexium buy topiramate pills for sale buy topamax online

  51. Gyndnd说道:

    pepcid 40mg canada buy pepcid without prescription buy cheap generic tacrolimus

  52. Fjqpbd说道:

    cost xenical 120mg purchase diltiazem online cheap buy generic diltiazem over the counter

  53. Stzdaz说道:

    purchase warfarin coumadin 5mg pills buy metoclopramide 20mg for sale

  54. Rhmcjn说道:

    glimepiride 4mg for sale amaryl 1mg brand order arcoxia 60mg for sale

  55. Hzgolz说道:

    nortriptyline pills anacin 500mg pills order generic panadol

  56. Nspqir说道:

    buy inderal pill how to buy nurofen clopidogrel 75mg for sale

  57. Vjluym说道:

    oral fosamax 70mg colchicine 0.5mg drug furadantin order online

  58. Yjacry说道:

    buy claritin 10mg generic loratadine generic dapoxetine 30mg uk

  59. Sxxgbe说道:

    baclofen over the counter generic lioresal ketorolac usa

  60. Imkafz说道:

    lioresal for sale online oral endep order toradol online

  61. abard说道:

    “와이즈1xbet 넷마블”,” “,1x-bet-1
    https://micro.blog/betx
    “1xbet н•ёл””мєЎ лњ»”,”1XBET 홈페이지에 들어가 мљ°мёЎ мѓЃл‹Ём—ђ мћ€лЉ” “로그인” лІ„нЉјмќ„ нЃґл¦­н•ґ лЎњк·ёмќёмќ„ 합니다. нљЊм›ђк°Ђмћ…мќ„ м•„м§Ѓ 하지 м•ЉмќЂ кІЅмљ°м—” лЎњк·ёмќё лІ„нЉј мљ°мёЎм—ђ мћ€лЉ” “가입” лІ„нЉјмќ„ нЃґл¦­н•ґ 1XBET к°Ђмћ…мќ„ лЁјм Ђ 합니다. лЎњк·ёмќёмќ„ н•њ н›„ 1XBET мћ…кё€мќ„ 합니다. мћ…кё€мќЂ н•њкµ­ мќЂн–‰ кі„мўЊмќґмІґк°Ђ к°ЂлЉҐн•ґ 빠르고 м‰ЅкІЊ 가능합니다. 하프 кіЁ м•„м‹њм•„ н•ёл”” м—­м‹њ м•ЅнЊЂм—ђкІЊ 유리하고 к°•нЊЂм—ђкІЊ 불리하게 н•ёл””мєЎмќ„ м Ѓмљ© 시킵니다. 하프라는 의미대로 정수를 사용하는게 м•„л‹Њ 0.5 л‹Ёмњ„ кё°м¤ЂмњјлЎњ н•ёл””мєЎмќ„ 설정하게 됩니다.”,1x-bet-1

  62. Qxnvnt说道:

    perindopril 4mg tablet purchase coversyl for sale buy generic allegra for sale

  63. Mfaydx说道:

    cheap dilantin 100 mg buy generic cyclobenzaprine oxybutynin 5mg cost

  64. Gfshyy说道:

    buy methylprednisolone tablets buy adalat 30mg generic order aristocort 4mg pills

  65. Ltjbdw说道:

    buy levitra 10mg pill brand zanaflex buy zanaflex no prescription

  66. Izjvxq说道:

    order serophene generic imuran canada order imuran 50mg generic

  67. Uykdpl说道:

    order amantadine 100 mg online atenolol 50mg price buy dapsone online cheap

  68. Wdcuql说道:

    online gambling sites buy synthroid without prescription levothyroxine price

  69. Pynetq说道:

    hollywood casino online wind creek casino online play stromectol 3 mg price

  70. Dcbamt说道:

    buy protonix paypal protonix 40mg cheap phenazopyridine 200 mg usa

  71. Sujcrt说道:

    real money casino online online blackjack for money purchase albuterol

  72. Rzsafn说道:

    play roulette casino real money purchase furosemide generic

  73. Ewsyut说道:

    atorvastatin 40mg cheap norvasc 10mg brand order amlodipine 5mg

  74. Oyqzdc说道:

    buy azipro 500mg online cheap buy prednisolone 40mg generic cheap neurontin 600mg

  75. Bxllmr说道:

    cheap omnicef 300 mg omnicef pill lansoprazole 15mg cheap

  76. Hidlvv说道:

    order generic accutane 10mg accutane 40mg drug azithromycin 500mg tablet

  77. Fvjbis说道:

    modafinil 200mg canada deltasone drug prednisone 5mg cheap

  78. Ssqbxa说道:

    cenforce 50mg ca buy cenforce generic buy cheap aralen

  79. Ebckxv说道:

    buy micardis cheap plaquenil 400mg without prescription order movfor sale

  80. Tgiluy说道:

    tadalafil online order sildenafil 50mg online brand sildenafil

  81. Pookrf说道:

    buy generic prilosec 10mg buy metoprolol 50mg pill lopressor 100mg tablet

  82. Ognwdi说道:

    purchase premarin online dostinex buy online order sildenafil 50mg

  83. Mmhkde说道:

    zovirax without prescription purchase zovirax generic exelon over the counter

  84. Cailbd说道:

    ferrous 100mg cheap buy betapace pills order betapace 40 mg generic

  85. Jryhpe说道:

    generic pyridostigmine rizatriptan order oral maxalt 5mg

  86. Mzsumw说道:

    prasugrel 10mg cost purchase detrol tolterodine 2mg sale

  87. Kqqlti说道:

    fludrocortisone usa aciphex 20mg canada buy loperamide 2 mg for sale

  88. Wndccd说道:

    buy etodolac 600 mg without prescription how to buy colospa buy pletal 100 mg generic

  89. Dekgzd说道:

    buy dydrogesterone 10 mg for sale purchase dydrogesterone generic buy jardiance 25mg pills

  90. Atrjte说道:

    brand dipyridamole 100mg buy pravastatin pills order pravachol 10mg

  91. Jsgsio说道:

    order meloset 3mg pills danazol brand buy danazol pills

  92. Xjphez说道:

    precose 25mg usa acarbose 50mg over the counter brand fulvicin 250 mg

  93. Vuihkv说道:

    order aspirin online cheap oral aspirin purchase zovirax cream

  94. Zkjpct说道:

    purchase minoxytop generic order flomax online cheap top ed pills

  95. Elgasd说道:

    order ketotifen without prescription ziprasidone 80mg sale buy imipramine 25mg online

  96. Zsgutn说道:

    buy fenofibrate 160mg online buy generic tricor fenofibrate order online

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

CAPTCHAis initialing...